[英]Angular 2 CanActivate is called twice
I am faced with a problem with route guards with Angular. 我遇到了使用Angular的路线防护问题。
My CanActivate guard is called twice when navigating to a page that is not permitted because I'm not logged in. 导航到不允许的页面时,我的CanActivate防护被调用两次,因为我没有登录。
I have 1 root module and provided there my CanActivate guard and other services. 我有1个根模块,并提供了我的CanActivate后卫和其他服务。
Thank you in advance! 先感谢您!
Here is my router: 这是我的路由器:
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});
and guard: 守卫:
@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: 虽然这不是一个解决方案,但它是一个答案:
This happens when using hash routing (useHash: true). 使用散列路由时会发生这种情况(useHash:true)。
It may be a bug in the Angular router. 它可能是Angular路由器中的一个错误。
I am still investigating to see if there is a solution. 我还在调查是否有解决方案。
Steve 史蒂夫
I noticed it will not work with Hash: Below is my example, and notice: the code below will call penModalDialogInvalid() twice as I use 我注意到它不适用于Hash:下面是我的示例,并注意:下面的代码将调用penModalDialogInvalid()两次,因为我使用
providers: [{provide:LocationStrategy,useClass:HashLocationStrategy}],
@Injectable()
export class UserDetailsGuard implements CanActivate {
constructor(private _router:Router,
private winRef: WindowRef){}
canActivate(route:ActivatedRouteSnapshot,state: RouterStateSnapshot ) : boolean {
let id=+route.url[0].path;
if (isNaN(id) || id <1 ){
this.winRef.nativeWindow.openModalDialogInvalid();
//this._router.navigate(['/pagenotfound']);
return false;
}
return true;
}
}
If I comment out the navigation line above, it will call the function once!!!! 如果我注释掉上面的导航线,它将调用该函数一次!!!! otherwise twice except in Firefox and all Firefox-based browsers!!!!
否则两次,除了在Firefox和所有基于Firefox的浏览器!!!! why????
为什么???? I dunno!!!!!
我不知道!!!!!
请在路由链接之前重新删除斜杠。
redirectTo: "meal-list"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.