我尝试使用 custom reuse strategy在我的 angular2 项目中, 但我发现它不适用于惰性模块加载。 有谁知道这件事吗?我的项目是 angular 2.6.4
重用策略.ts
import {RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle} from "@angular/router";
export class CustomReuseStrategy implements RouteReuseStrategy {
handlers: {[key: string]: DetachedRouteHandle} = {};
shouldDetach(route: ActivatedRouteSnapshot): boolean {
console.debug('CustomReuseStrategy:shouldDetach', route);
return true;
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
console.debug('CustomReuseStrategy:store', route, handle);
this.handlers[route.routeConfig.path] = handle;
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
console.debug('CustomReuseStrategy:shouldAttach', route);
return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
console.debug('CustomReuseStrategy:retrieve', route);
if (!route.routeConfig) return null;
return this.handlers[route.routeConfig.path];
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr);
return future.routeConfig === curr.routeConfig;
}
}
应用程序模块.ts
const appRoutes: Routes = [
{ path: 'crisis-center', component: CrisisListComponent },
{ path: 'heroes', loadChildren: 'app/hero-list.module#HeroListModule' },
{ path: '', redirectTo: '/crisis-center', pathMatch: 'full' }
];
@NgModule({
imports: [ ... ],
declarations: [ ... ],
providers:[
{provide: RouteReuseStrategy, useClass: CustomReuseStrategy}
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
我把<input>
到这两个组件,我测试了它。
在CrisisListComponent
中输入的值已存储,但是 HeroListComponent lazy-loaded
的值没有保留。
我不知道它还不被支持。 谢谢你帮助我。
最佳答案
RouteReuseStrategy
确实适用于 LazyLoaded 组件。
这里的问题是您使用 route.routeConfig.path
作为存储和检索句柄的键。
我不知道为什么,但是对于 LazyLoaded 模块,route.routeConfig.path
在执行 shouldAttach
时是空的
我使用的解决方案是在我的路由中定义一个自定义键,例如:
{ path: '...', loadChildren: '...module#...Module', data: { key: 'custom_key' } }
可以在 ActivatedRouteSnapshot
中轻松访问此键值,例如:
route.data.key
使用此 key ,您可以正确存储和检索句柄。
关于Angular2 不适用于延迟模块加载的自定义重用策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42383546/