Angular 2 CanActivate被调用两次

问题描述 投票:8回答:3

您好我遇到了问题。当我尝试导航到不被允许的页面时,我的CanActivate警卫会被调用两次,因为我没有登录。

我有1个根模块,并提供了我的CanActivate后卫和其他服务。

先感谢您!

这是我的路由器:

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;
  }
}
angular angular2-routing
3个回答
2
投票

虽然这不是一个解决方案,但它是一个答案:

使用散列路由时会发生这种情况(useHash:true)。

它可能是Angular路由器中的一个错误。

我还在调查是否有解决方案。

史蒂夫


1
投票

我注意到它不适用于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;

} 

}

如果我注释掉上面的导航线,它将调用该函数一次!!!!否则两次,除了在Firefox和所有基于Firefox的浏览器!!!!为什么????我不知道!!!!!


0
投票

请在路由链接之前重新删除斜杠。

redirectTo: "meal-list"
© www.soinside.com 2019 - 2024. All rights reserved.