之前做过一个 Angular 下的路由重用,即记录 SPA 应用的上一个页面的内容。最开始的时候,并没有考虑 Lazyload,因此实现起来就比较简单:
export class SimpleReuseStrategy implements RouteReuseStrategy {
public static handlers: { [key: string]: DetachedRouteHandle } = {};
public shouldDetach(route: ActivatedRouteSnapshot): boolean {
return true;
}
public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
SimpleReuseStrategy.handlers[route.routeConfig.path] = handle;
}
public shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!route.routeConfig && !!SimpleReuseStrategy.handlers[route.routeConfig.path];
}
public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
if (!route.routeConfig) {
return null;
}
return SimpleReuseStrategy.handlers[route.routeConfig.path];
}
public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
}
}
后来项目中添加了 Lazyload,因此便添加了一个 reusePath 的参数来控制是否缓存,最后实现如下:
export class SimpleReuseStrategy implements RouteReuseStrategy {
public static handlers: { [key: string]: DetachedRouteHandle } = {};
public shouldDetach(route: ActivatedRouteSnapshot): boolean {
if (!!route.data && !!route.data.reusePath) {
return true;
}
return false;
}
/** 当路由离开时会触发。按reusePath作为key存储路由快照&组件当前实例对象 */
public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
SimpleReuseStrategy.handlers[route.data.reusePath] = handle;
}
/** 若 path 在缓存中有的都认为允许还原路由 */
public shouldAttach(route: ActivatedRouteSnapshot): boolean {
if (!!route.data.reusePath && !!SimpleReuseStrategy.handlers[route.data.reusePath]) {
return true;
}
return false;
}
/** 从缓存中获取快照,若无则返回nul */
public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
if (!!route.data && !!route.data.reusePath) {
return SimpleReuseStrategy.handlers[route.data.reusePath];
}
return null;
}
/** 进入路由触发,判断是否同一路由 */
public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
if (future.data && curr.data && future.data.reusePath && curr.data.reusePath) {
return future.data.reusePath === curr.data.reusePath;
}
return false;
}
}
为了保存路由,需要单独额外的 在 Routing 里 添加一个 key :
const routes: Routes = [
{
data: { reusePath: 'hello/hello' },
path: 'hello/hello',
loadChildren: './hello/hello.module#CheckinModule'
}
]
围观我的Github Idea墙, 也许,你会遇到心仪的项目