Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 CanActivate is called twice

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;
  }
}
like image 707
Simon Avatar asked Oct 31 '16 18:10

Simon


1 Answers

Please reomove slash before the route link.

redirectTo: "meal-list"
like image 77
Mamunur Rashid Avatar answered Oct 27 '22 11:10

Mamunur Rashid