Angular 2. CanActivate仅在加载时调用

时间:2017-07-05 06:13:11

标签: angular

我有以下导入到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);

如你所见,我有canActivate。我注意到,当我第一次打开应用程序或在浏览器中写入地址时调用AuthGuard,但如果我使用我的菜单更改URL,则不会调用AuthGuard

 <a routerLink="/cars">

我做错了什么?

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

1 个答案:

答案 0 :(得分:3)

似乎CanActivate仅在父空路线上设置。如果您希望在子路径之间导航时再次执行,请考虑改为使用canActivateChild