我有一条主路线,它有子路线,而那些孩子是延迟加载的模块,在每个延迟加载的模块中,我也有单独的路由。我遇到的问题是当我保护主路线以防止加载多次调用的子路径时
主要路由代码
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函数多次调用为什么?
答案 0 :(得分:1)
你有两个级别的激活路线,所以它将检查每个级别的守卫。如果您想要将其召唤一次,只需将警卫向下移动到子级别。
答案 1 :(得分:0)
@Adawg的意思是:
path: '',
component: CourseListComponent,
resolve: { courses: CourseListResolver },
canActivateChild:[AuthGuard],
children: [
在延迟加载的路由部分而非根路由中放入 canactivatechild