user348173
user348173

Reputation: 9288

Angular 2. CanActivate is called on load only

I have the following routing that I import to Application Component:

const routes: Routes = [
  {
    path: '',
    component: MainLayoutComponent,
    children: [
      {
        path: '', redirectTo: 'main', pathMatch: 'full'
      },
      {
        path: 'main', loadChildren: 'app/main/main.module#MaindModule'
      },
      {
        path: 'cars', loadChildren: 'app/cars/cars.module#CarsModule'
      }  
    ],
    canActivate: [AuthGuard]    
  },
  {
    path: 'auth',
    component: EmptyLayoutComponent,
    loadChildren: 'app/auth/auth.module#AuthModule'
  },
  {
    path: '**',
    redirectTo: 'main'
  }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

As you can see I have canActivate. I noticed that AuthGuard is called when I open application in first time or write address in the browser, but if I use my menu to change url then AuthGuard is not called:

 <a routerLink="/cars">

What I have done wrong?

AuthGuard:

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService,
              private router: Router) {}

  canActivate() {
    if (!this.authService.authenticated) {
      this.router.navigate(['/auth/login']);
      return false;
    }
    return true;
  }
}

Upvotes: 0

Views: 700

Answers (1)

DeborahK
DeborahK

Reputation: 60596

It appears that CanActivate is only set on the parent empty route. If you want it to execute again when navigating between child routes, consider using canActivateChild instead.

Upvotes: 3

Related Questions