Angular 2 CanActivate 被调用两次 [英] Angular 2 CanActivate is called twice
本文介绍了Angular 2 CanActivate 被调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用 Angular 的路由守卫方面遇到了问题.
I am faced with a problem with route guards with Angular.
导航到由于我未登录而不允许的页面时,我的 CanActivate 守卫被调用两次.
My CanActivate guard is called twice when navigating to a page that is not permitted because I'm not logged in.
我有 1 个根模块,并在那里提供了我的 CanActivate 防护和其他服务.
I have 1 root module and provided there my CanActivate guard and other services.
先谢谢你!
这是我的路由器:
const appRoutes: Routes = [
{
path: "",
pathMatch: "full",
redirectTo: "/meal-list",
},
{
path: "login",
component: LoginComponent,
},
{
path: "meal-list",
component: MealListComponent,
canActivate: [AuthActivateGuard],
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: true});
和守卫:
@Injectable()
export class AuthActivateGuard implements CanActivate {
constructor(private authService: AuthService,
private router: Router) {
console.log("guard created");
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|boolean {
if (!this.authService.authenticated) {
return this.authService.checkLogged().map(res => {
this.authService.authenticated = true;
return true;
}).catch(()=> {
this.authService.authenticated = false;
this.router.navigate(["login"]);
return Observable.of(false);
});
}
return true;
}
}
推荐答案
虽然这不是解决方案,但它是一个答案:
Although this is not a solution, it is an answer:
使用哈希路由时会发生这种情况(useHash: true).
This happens when using hash routing (useHash: true).
这可能是 Angular 路由器中的一个错误.
It may be a bug in the Angular router.
我仍在调查是否有解决方案.
I am still investigating to see if there is a solution.
史蒂夫
这篇关于Angular 2 CanActivate 被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文