angular – 子模块中的RouteReuseStrategy
发布时间:2020-12-17 07:15:56 所属栏目:安全 来源:网络整理
导读:这是我的懒惰加载子模块: @NgModule({ imports: [ CommonModule,RouterModule.forChild(acnpRoutes),.... ],declarations: [...],providers: [ {provide: RouteReuseStrategy,useClass: ACNPReuseStrategy} ]})export class AddCustomerNaturalPersonModule
这是我的懒惰加载子模块:
@NgModule({ imports: [ CommonModule,RouterModule.forChild(acnpRoutes),.... ],declarations: [...],providers: [ {provide: RouteReuseStrategy,useClass: ACNPReuseStrategy} ] }) export class AddCustomerNaturalPersonModule { } 路线: const acnpRoutes: Routes = [ { path: '',component: AddCustomerNaturalPersonComponent,children: [ { path: 'stepOne',component: ACNPStepOneComponent },{ path: 'stepTwo',component: ACNPStepTwoComponent },] } ] 和ACPNReuseStrategy: export class ACNPReuseStrategy implements RouteReuseStrategy { handlers: {[key: string]: DetachedRouteHandle} = {} shouldDetach(route: ActivatedRouteSnapshot): boolean { console.log(1) return true; } store(route: ActivatedRouteSnapshot,handle: {}): void { console.log(2) } ... shouldReuseRoute(future: ActivatedRouteSnapshot,curr: ActivatedRouteSnapshot): boolean { console.log(5) } } 不幸的是,ACNPReuseStrategy方法中的这些console.log都没有被触发.这是为什么?是否可以在延迟加载的模块中重用组件? 解决方法
TL; DR在主模块中提供RouteReuseStrategy而不是子模块(默认情况下为app.module.ts).然后,为每个路由分配route.data中的密钥以区分您的路由.
我最近也遇到过这个问题.我的子模块安装在主应用程序路由下,如下所示: ...,{ // in app.route.ts path: 'apimarket',canActivate: [DeveloperResolve],loadChildren: './apimarket/apimarket.module#ApiMarketModule' } 如果我在子模块ApiMarketModule中提供自定义的RouteReuseStrategy,则永远不会构造RouteReuseStrategy. 解决方案是在主模块中提供策略而不是子模块(在我的情况下为app.module.ts).然后你的RouteReuseStrategy将被正确构建. 但是,由于route.routeConfig.path是因为您的子路由而相对路径,因此策略将无法按预期工作.要解决这个问题,我的解决方案是为我的路线分配一个唯一的键,如下所示: export const apimarketRoutes: Routes = [ { path: '',component: ApiMarketComponent,data: { shouldReuse: true,key: 'apimarketroot' } },{ path: ':id',component: ContentPageComponent,} ]; 这是我的RouteReuseStrategy实现FYR export class MyRouteReuseStrategy implements RouteReuseStrategy { handlers: {[key: string]: DetachedRouteHandle} = {}; constructor() { console.log('constructed'); } retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { if (!route.data['shouldReuse']) { return null; } console.log('Attach cached page for: ',route.data['key']); return this.handlers[route.data['key']]; } store(route: ActivatedRouteSnapshot,handle: DetachedRouteHandle): void { if (route.data['shouldReuse']) { this.handlers[route.data['key']] = handle; } } shouldDetach(route: ActivatedRouteSnapshot): boolean { return !!route.data['shouldReuse']; } shouldAttach(route: ActivatedRouteSnapshot): boolean { return !!route.data['shouldReuse'] && !!this.handlers[route.data['key']]; } shouldReuseRoute(future: ActivatedRouteSnapshot,current: ActivatedRouteSnapshot): boolean { return !!future.data['shouldReuse']; } } (RouteReuseStrategy没有详细记录,由于策略在根级别工作,我的解决方案可能存在潜在的性能问题.欢迎讨论:)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |