Angular 2 CanActivate called twice

I ran into a problem with route guards with Angular.

My CanActivate guard is called twice when I go to a page that is not allowed because I have not logged in.

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

Thanks 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; } } 
+9
source share
3 answers

Although this is not a solution, this is the answer:

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

This may be a bug in the Angular router.

I am still investigating if there is a solution.

Steve

+2
source

I noticed that this will not work with Hash: The following is my example, and note: 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 for Firefox and all Firefox-based browsers !!!! What for???? I dont know!!!!!

+1
source

Please rewind the slash before the route link.

 redirectTo: "meal-list" 
0
source

Source: https://habr.com/ru/post/1011894/


All Articles