{ path: 'portal', component: PortalComponent, canActivate: [AuthGuard] }
这是AuthGuard:
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private appState: ApplicationState, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): Observable<boolean> {
return this.appState.User.map(
(user) => {
if (user.UserToken) return true;
this.navToLogin(url);
return false;
}
);
}
private navToLogin(redirUrl: string) {
this.appState.RedirectUrl = redirUrl;
this.router.navigate(['/']);
}
}
在这里,您可以从...获取用户的
@Injectable()
export class ApplicationState {
private _user: BehaviorSubject<LoginUser> = new BehaviorSubject<LoginUser>(new LoginUser());
get User() {
return this._user.asObservable();
}
}
如果UserToken存在于User对象上,我希望用户能够访问/ portal路由。但是,如果令牌不存在,我希望用户导航到登录页面(默认路由/)。
我尝试点击了/ portal的链接。 checkLogin()中的appState.User.map返回true,但应用程序永远不会导航到/ portal。
我做错了什么?这是其中一个&#34;冷可观察&#34;的情况?
答案 0 :(得分:1)
试试这个:
@Injectable()
export class ApplicationState {
private _user: BehaviorSubject<LoginUser> = new BehaviorSubject<LoginUser>(new LoginUser());
get User() {
return this._user.value;
}
// login(user: LoginUser) { this._user.next(user); }
}
@Injectable()
export class AuthGuard implements CanActivate {
// ...
checkLogin(url: string): boolean {
if (this.appState.User.UserToken) return true;
this.navToLogin(url);
return false;
}
// ...
}