无法使应用导航到门户 [英] Can't get app to navigate to portal
问题描述
我正在尝试写一个路由守卫.这是我的路线...
I'm trying to write a route guard. Here's my route...
{ path: 'portal', component: PortalComponent, canActivate: [AuthGuard] }
这是AuthGuard:
And here's 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(['/']);
}
}
这是ApplicationState,您可以从其中获取用户...
And here's ApplicationState where you get the User from...
@Injectable()
export class ApplicationState {
private _user: BehaviorSubject<LoginUser> = new BehaviorSubject<LoginUser>(new LoginUser());
get User() {
return this._user.asObservable();
}
}
如果User对象上存在UserToken,我希望用户能够访问/portal路由.但是,如果令牌不存在,我希望用户导航到登录页面(默认路由/).
I want the user to be able to access the /portal route if the UserToken exists on the User object. However, if the token does not exist, I want the user to navigate to the login page (default route /).
我有一个尝试单击的/portal链接.并且checkLogin()中的appState.User.map返回true,但是,该应用程序永远不会导航到/portal.
I have a link to /portal that I tried clicking. And the appState.User.map inside checkLogin() returns true, however, the app never navigates to /portal.
我做错了什么?这是冷可观察"情况之一吗?
What am I doing wrong? Is this one of those "cold observable" situations?
推荐答案
尝试一下:
@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;
}
// ...
}
这篇关于无法使应用导航到门户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!