Have a problem with Angular 17 Guards, can't make private route

126 views Asked by At

Made a phonebook with authorizations, and used Guards for routing. When i try to navigate (no authorizate) to contacts through the link, everything is ok. But when i write in adress bar route ...../contacts it is working and navigate me there.

i tried different types of authGuards, but the result is the same



import { CanActivateFn } from '@angular/router';
import { inject } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import { map } from 'rxjs';

export const authGuardGuard: CanActivateFn = (  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean => {
  const router = inject(Router) 
  const authService = inject(AuthService)
  return authService.isAuthenticatedUser().pipe(
      map((isAuthenticated: boolean) => {
        if (isAuthenticated) {
          return true;
        } 
          router.createUrlTree(['/login']);
          return false;
      })
    );
  }


import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, throwError, of} from 'rxjs';
import { tap } from 'rxjs';
import { catchError } from 'rxjs';

import { HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  isAuthenticated: boolean = false;
  baseUrl = '*****************************';
   private tokenKey = 'authToken';

  constructor(private http: HttpClient) { }

  login(credentials: { email: string, password: string }): Observable<any> {

    return this.http.post<any>(`${this.baseUrl}/users/login`, credentials).pipe(tap(response => {
      console.log('Login successful', response);
      
    
      if (response.token) {
        this.isAuthenticated = true;
        localStorage.setItem(this.tokenKey, response.token);
      }
      return response
    }))
  }

 isAuthenticatedUser(): Observable<boolean> {
    return of(!!localStorage.getItem(this.tokenKey));
  }

  getToken(): string | null {
    return localStorage.getItem(this.tokenKey);
  }

  logout(): void {
    this.isAuthenticated = false;
    localStorage.removeItem(this.tokenKey);
  }
}


import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { ContactsComponent } from './contacts/contacts.component';
import { authGuardGuard } from './auth-guard.guard';

export const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'contacts', component: ContactsComponent, canActivate: [authGuardGuard]},
  { path: 'login', component:  LoginComponent},
  { path: 'register', component:  RegisterComponent}
];

0

There are 0 answers