使用与主组件相同的条件修改auth guard。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let currentUser = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')): null;
if (currentUser && currentUser.token != "fake-jwt-token") {
// logged in and doesn't have fake token
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
要做到这一点,一个简单而干净的方法是为家庭成员配备单独的警卫。
@Injectable({ providedIn: 'root' })
export class HomeGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let currentUser = localStorage.getItem('currentUser');
if (currentUser) {
// logged in so return true
return true;
}
return false;
}
}
你的路线是:
const appRoutes: Routes = [
{ path: '', component: HomeComponent, canActivate: [HomeGuard] },
{ path: 'login', component: LoginComponent },
{ path: 'user', component: UserComponent, canActivate: [AuthGuard] },
// otherwise redirect to home
{ path: '**', redirectTo: '' }
];
请参见以下示例:
https://stackblitz.com/edit/angular-6-jwt-authentication-example-42ft5j?file=app%2F_guards%2Fhome.guard.ts