protect page in agnular when user didn't login
by bilal4 Updated: Feb 2, 2023
Guide Kit
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
if (!this.isAuthenticated()) {
this.router.navigate(['/login']);
return false;
}
return true;
}
isAuthenticated(): boolean {
// Check if the user is authenticated,
// for example by checking local storage or a session cookie.
return !!localStorage.getItem('token');
}
}