我正在尝试在导航到儿童路线之前解决数据,因为我必须在儿童看守中使用该数据。问题是父解析器,在儿童警卫被解雇后解析数据。解析器需要很长时间来解析数据
// app.module.ts
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{
path: '',
component: SiteLayoutComponent,
children: [
{ path: '', redirectTo: 'warehouse', pathMatch: 'full' },
{
path: 'warehouse',
loadChildren: './warehouse/warehouse.module#WarehouseModule'
// loadChildren: () => WarehouseModule
}
],
canActivate: [AuthGuard],
resolve: {
Site: SiteResolver // should be resolved before the guard is invoked.
}
},
{ path: '**', component: PageNotFoundComponent }
];
// warehouse.module.ts
const appRoutes: Routes = [
{ path: '', redirectTo: 'cash', pathMatch: 'full' },
{ path: 'cash', component: CashComponent, canActivate: [RouteGuard] // should be invoked after the parent resolver resloves th data }
];
这里,父子解析器即SiteResolver在子防护之后解析,即调用RouteGuard。我想要的是SiteResolver首先解析数据,然后RouteGuard应该触发,我该如何实现?
答案 0 :(得分:3)
我不确定这是否是正确的方法。但是在经历了许多棘手的问题之后,我找到了解决方法。
使用canActivate而不是resolve来获取数据并将数据存储在服务中。下面是相同的代码段
@Injectable()
export class FetchUserData implements CanActivate {
constructor(
private userService: UserService,
private httpClient: HttpClient
) {}
public modalRef: BsModalRef;
canActivate() {
return this.httpClient
.get("some/api/route")
.map(e => {
if (e) {
this.userService.setUserDetails(e);
return true;
}
return true;
})
.catch(() => {
return Observable.of(false);
});
}
}
对我来说效果很好。刷新子路由将没有问题。