TL;DR提供您的RouteReuseStrategy
在主模块而不是子模块中(app.module.ts
默认情况下)。然后,为每条路线分配一个key
in route.data
使您的路线与众不同。
我最近也遇到了这个问题。我的子模块安装在主应用程序路由下,如下所示:
..., { // in app.route.ts
path: 'apimarket',
canActivate: [DeveloperResolve],
loadChildren: './apimarket/apimarket.module#ApiMarketModule'
}
如果我提供我的定制RouteReuseStrategy
在子模块中ApiMarketModule
, the RouteReuseStrategy
永远不会被建造。
解决方案是在主模块而不是子模块中提供策略(app.module.ts
就我而言)。那么你的RouteReuseStrategy
将被正确构建。
然而,由于以下原因,该策略不会按预期发挥作用:route.routeConfig.path
由于您的子路线,因此是相对路径。为了解决这个问题,我的解决方案是分配一个唯一的key
我的路线是这样的:
export const apimarketRoutes: Routes = [
{
path: '',
component: ApiMarketComponent,
data: {
shouldReuse: true,
key: 'apimarketroot'
}
},
{
path: ':id',
component: ContentPageComponent,
}
];
这是我的RouteReuseStrategy
实施前两年
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
没有很好的记录,由于策略在根级别上工作,我的解决方案可能存在潜在的性能问题。欢迎讨论:))