Angular 2 CanActivate is called twice

前端 未结 3 1301
南方客
南方客 2021-02-20 09:20

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

相关标签:
3条回答
  • 2021-02-20 09:51

    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!!!!!

    0 讨论(0)
  • 2021-02-20 10:05

    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

    0 讨论(0)
  • 2021-02-20 10:05

    Please reomove slash before the route link.

    redirectTo: "meal-list"
    
    0 讨论(0)
提交回复
热议问题