Angular 2 Routing Guard CanActivateChild 与延迟加载模块路由

标签 angular angular2-routing lazy-loading

我有一个主路由,其中​​有子路由,这些子路由是延迟加载的模块,并且在每个延迟加载的模块中,我也为它们提供了单独的路由。我遇到的问题是当我保护主路由以防止加载它多次调用的子路由时

主要路由代码

export const PROVIDER_ROUTES: Route = {
    path: 'provider',
    component: ProviderComponent,
    canActivateChild:[AuthGuard],
    children: [
        { path: '', redirectTo: 'courses', pathMatch: 'full' },
        { path: 'courses', loadChildren: 'app/provider/course/course.module#CourseModule' },

    ],

};

延迟加载路由代码

const routes: Routes = [
  {
    path: '',
    component: CourseListComponent,
    resolve: { courses: CourseListResolver },
    children: [
      {
        path: ':id',
        component: CoursesEditComponent,
        resolve: { organizations: AddCourseResolver }
      },
      {
        path: ':id/edit',
        component: CoursesEditComponent,
        resolve: { course: CourseEditResolver }
      },
      {
        path: ':id/assign/:orgId',
        component: CourseAssignComponent,
        resolve: { subOrganizations: LicenseAssignResolver }
      },
      {
        path: ':id/update/:orgId',
        component: CourseAssignComponent,
        resolve: { license: LicenseEditResolver }
      }

    ]
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  providers: [
    CourseListResolver,
    CourseEditResolver,
    LicenseAssignResolver,
    LicenseEditResolver,
    AddCourseResolver
  ],
  exports: [RouterModule],
})
export class CourseRoutingModule { }

export const RoutedComponents = [
  CourseListComponent,
  CoursesEditComponent,
  CourseAssignComponent
];

AuthGuard 代码是

export class AuthGuard implements CanActivateChild {

  constructor(private authService: AuthService, private router: Router, private commonService:CommonService) { }
  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.authService.isUserLoggedIn().map((result: EditUser) => {
      console.log(result);
      if (result != null && result.organizations.length > 0) {
        this.commonService.isAuthenticated = true;
        return true;
      }
      this.commonService.isAuthenticated = false;
      this.router.navigate(["/provider"])
      return false;
    });

AuthGuard 函数为何被多次调用?

enter image description here

最佳答案

您有 2 级激活的路线,因此它将检查每个级别的守卫。如果你想让它调用一次,只需将守卫向下移动到子级即可。

关于Angular 2 Routing Guard CanActivateChild 与延迟加载模块路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46690416/

相关文章:

Angular 如何根据路线更改导航菜单标题

angular - 在功能模块中延迟加载 Angular Material

NHibernate - 访问关联对象的 ID 而不延迟加载整个对象

java - JPA+Hibernate 强制 JPA 在延迟加载时不使用代理

angular - 如何在 Angular 7 的页面加载时打开 ng-bootstrap 模式弹出窗口?

css - Angular2 在组件外部更改父样式

angular - 如何将 gulp 任务添加到 Angular cli 构建中

angular - 路由和模块

angular - 如何处理2 ipcRenderer.send调用到1 ipcMain.on

node.js - Angular 2 路由器 : Cannot match any routes