在加载应用程序之前,我想检查用户是否已登录并加载一些数据。因此,我在顶部路线上放了两名警卫,但他们没有被执行。是不是可以将canActivate放在顶级路线上?在何处放置警卫是否有任何限制?
路线配置
export const routes = [
{
path: '',
canActivate: [IsAuthenticatedGuard, IsDataLoadedGuard],
children: [
{
path: '',
redirectTo: '/something',
pathMatch: 'full'
}
]
}
];
/ something是不同模块的一部分,路由使用RouterModule.forChild()
加载到另一个模块中卫兵
@Injectable()
export class IsAuthenticatedGuard implements CanActivate {
constructor(private _router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
if (!this._isSignedIn()) {
window.location.replace('/signin.html');
return Observable.of(false);
}
return Observable.of(true);
}
_isSignedIn(): boolean {
return document.cookie.indexOf('jwt_cookie') !== -1;
}
}
@Injectable()
export class IsDataLoadedGuard implements CanActivate {
private homeState$: Observable<IHomeState>;
constructor(private _router: Router, private _store: Store<IAppState>) {
this.homeState$ = _store.select('home');
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
return this.homeState$.map((homeState: IHomeState) =>
!homeState.get('loading') || homeState.hasIn(['home', 'id'])
);
}
}
应用确实会重定向到/something
,而实际应该重定向到/signin.html
。我做错了什么?