0

Im trying to implement a guard on my angular 9 project to check if the user is authenticated, but the canActivate method is not being invoked on the "sample" route that i'm trying to guard.

this is my main module where i'm trying to implement the guard:

const appRoutes: Routes = [
    ...
    {
        path      : 'sample',
        component: SampleComponent,
        canActivate: [AuthGuard]
    },
    ...
];

@NgModule({
    ...
    providers   : [
        AuthGuard,
        ...
    ],
    exports     : [
        RouterModule
    ]
})
export class AppModule
{
}

this is the guard class:

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

    constructor(
        public authService: AuthService,
        public router: Router
    ) { }

    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
        if (this.authService.isAuthenticated !== true) {
            window.alert('Forbidden');
            this.router.navigate(['/auth/login']);
            return false;
        }
        return true;
    }
}

AuthService isAuthenticated and getToken methods

    get isAuthenticated(): boolean {
        console.log('token' + this.getToken());
        if (this.getToken() === null) {
            return false;
        }else{
            return !this.jwtHelper.isTokenExpired(this.getToken());
        }
    }

    getToken(): string {
        return localStorage.getItem('access_token');
    }

I don't know what i'm doing wrong, please help me.

0 Answers0