我只想对一个模块使用此自定义路由重用策略:
export class CustomRouteReuseStrategy extends RouteReuseStrategy {
public shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; }
public store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {}
public shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; }
public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { return null; }
public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return true;
}
}
因此,我已经在名为
ChildModule
的模块之一中将@NgModule()传递给了:providers: [
{
provide: RouteReuseStrategy,
useClass: CustomRouteReuseStrategy
}
]
不幸的是,当我通过它时,它只是被忽略了。虽然将其添加到我的根
AppModule
时效果很好,但是我不确定它是否重要,但是ChildModule
延迟加载。怎么解决呢? 最佳答案
我最终通过将一些经过修改的CustomRouteStrategy
传递给AppModule
来实现了:
export class CustomRouteReuseStrategy extends RouteReuseStrategy {
public shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; }
public store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {}
public shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; }
public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { return null; }
public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return (future.routeConfig === curr.routeConfig) || future.data.reuse;
}
}
并将
data: { reuse: true }
添加到延迟加载的ChildModule
的路由中:{
path: 'some-path',
data: { reuse: true },
loadChildren: './child.module#ChildModule',
},
Demo with more advanced solution