Angular 2 CanActivate is called twice

拈花ヽ惹草 提交于 2019-12-22 03:51:25

问题


I am faced with a problem with route guards with Angular.

My CanActivate guard is called twice when navigating to a page that is not permitted because I'm not logged in.

I have 1 root module and provided there my CanActivate guard and other services.

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;
  }
}

回答1:


Although this is not a solution, it is an answer:

This happens when using hash routing (useHash: true).

It may be a bug in the Angular router.

I am still investigating to see if there is a solution.

Steve




回答2:


I noticed it will not work with Hash: Below is my example, and notice: the code below will call penModalDialogInvalid() twice as I use

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!!!! why???? I dunno!!!!!




回答3:


Please reomove slash before the route link.

redirectTo: "meal-list"


来源:https://stackoverflow.com/questions/40348132/angular-2-canactivate-is-called-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!