Reputation: 8730
My auth guard is
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class CheckToken implements CanActivate {
constructor(private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
var token = localStorage.getItem('id_token');
if(token) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
Issue is that line this.router.navigate(['/login'])
call infinite times and page break. It works fine but after updating angular-cli
this error occur
My routes
const appRoutes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full', canActivate: [CheckToken] },
{ path: 'login', component: LoginComponent },
{ path: 'logout', component: LogoutComponent },
];
Upvotes: 1
Views: 2651
Reputation: 12596
something go wrong these line
if(token && url=="/login"){
return true;
}
if user do not login -> token = null/undefined, -> loop forever.
try this:
if(token || url=="/login"){
return true;
}
EDIT
basically my issue is that I want when token exists and user again hit login url I want to redirect him to dashboard page
if(token) {
if (url=="/login") {
this.router.navigate(['/dashboard']);
}
return true;
}
or
redirect in LoginComponent
Upvotes: 2