[英]Angular 2. CanActivate is called on load only
我有以下導入到應用程序組件的路由:
const routes: Routes = [
{
path: '',
component: MainLayoutComponent,
children: [
{
path: '', redirectTo: 'main', pathMatch: 'full'
},
{
path: 'main', loadChildren: 'app/main/main.module#MaindModule'
},
{
path: 'cars', loadChildren: 'app/cars/cars.module#CarsModule'
}
],
canActivate: [AuthGuard]
},
{
path: 'auth',
component: EmptyLayoutComponent,
loadChildren: 'app/auth/auth.module#AuthModule'
},
{
path: '**',
redirectTo: 'main'
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
如您所見,我有canActivate
。 我注意到第一次打開應用程序或在瀏覽器中寫入地址時會調用AuthGuard
,但是如果我使用菜單更改url,則不會調用AuthGuard
:
<a routerLink="/cars">
我做錯了什么?
AuthGuard:
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService,
private router: Router) {}
canActivate() {
if (!this.authService.authenticated) {
this.router.navigate(['/auth/login']);
return false;
}
return true;
}
}
看來CanActivate
僅在父級空路由上設置。 如果您希望它在子路徑之間導航時再次執行,請考慮改用canActivateChild
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.