我在 Angular 4 中设置了两个守卫——一个在用户尝试访问受保护的路由时将用户重定向到登录页面,另一个将用户从“主页”重定向到欢迎页面(如果他们还没有到达那里)。
守卫本身工作得很好……但我注意到一些非常奇怪的行为。在 WelcomeTraveler 守卫中添加重定向this.router.navigate
会使应用程序处于我无法从第一个守卫访问受保护路由的状态,即使在登录后也是如此。我只是不断被发送回主页。
这是我的守卫:
export class AuthGuardLoggedInUser implements CanActivate {
private isLoggedIn: boolean;
private working: boolean;
constructor (@Inject(Store) private _store:Store<AppStore>, @Inject(Router) private _router: Router)
{
_store.select(state => state.AuthNState).subscribe(auth =>
{
this.isLoggedIn = auth.connected
this.working = auth.working
})
}
canActivate() {
if (this.working)
{
let promise: Promise<boolean> = new Promise((resolve, reject) => {
let sub = this._store.select(state => state.AuthNState).subscribe(auth =>
{
if (!auth.working) {
resolve(auth.connected)
sub.unsubscribe()
if (!auth.connected) this._router.navigate(['/i/login']);
}
})
});
return promise
}
else if (this.isLoggedIn){
return true
}
else {
this._router.navigate(['/i/login']);
}
export class WelcomeTraveler implements CanActivate {
private hasAlreadyVisitedWelcomePage: boolean;
private isLoggedIn: boolean;
private working: boolean;
constructor (@Inject(Store) private _store:Store<AppStore>, @Inject(Router) private _router: Router)
{
_store.select(state => state.AuthNState).subscribe(auth =>
{
this.isLoggedIn = auth.connected
this.working = auth.working
})
}
canActivate() {
if (this.working)
{
let promise: Promise<boolean> = new Promise((resolve, reject) => {
let sub = this._store.select(state => state.AuthNState).subscribe(auth =>
{
if (!auth.working) {
resolve(auth.connected)
sub.unsubscribe()
this.hasAlreadyVisitedWelcomePage = true
this._router.navigate(['/i/welcome']);
}
})
});
return promise
}
else if (this.isLoggedIn){
return true
}
else if (!this.hasAlreadyVisitedWelcomePage){
this.hasAlreadyVisitedWelcomePage = true
this._router.navigate(['/i/welcome']);
}
else return true
}
}
这是路由表的片段:
export var AppRoutes = RouterModule.forRoot([
{
path: '',
component: HomeComponent,
canActivate: [WelcomeTraveler]
}, {
path: 'i/getstarted',
component: GetStartedPageComponent,
canActivate: [AuthGuardLoggedInUser]
}, {
path: 'i/login',
component: LoginPageComponent
}, {
path: 'i/profile',
component: ProfilePageComponent,
canActivate: [AuthGuardLoggedInUser]
}, {
path: 'i/welcome',
component: WelcomePageComponent
}])
this.router.navigate
守卫中的存在WelcomeTraveler
似乎导致了问题,即使这些线从未被击中!登录后,我在尝试路由到个人资料后立即被送回“家”(成功通过第一个守卫后)。如果我删除导航线 - 问题就会消失。
有任何想法吗?