路由: | |
| |
路由的本质: | |
| |
RouteReuseStrategy(路由复用策略) | |
| |
基础的路由复用策略 | |
// 基础的路由复用策略 import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router'; export class SimpleReuseStrategy implements RouteReuseStrategy { _cacheRouters: { [key: string]: any } = {}; // 存储路由快照 /** * @description: 路由是否允许复用 * @param {type} route * @return: boolean true-允许 false-禁止 */ shouldDetach(route: ActivatedRouteSnapshot): boolean { return true; } /** * @description: 存储路由快照,路由离开时,触发; * 按path作为key存储路由快照&组件当前实例对象 * path等同RouterModule.forRoot中的配置 * @param {type} */ store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void { this._cacheRouters[route.routeConfig.path] = { snapshot: route,handle: handle,}; } /** * @description: 是否允许还原路由快照 * 在缓存中有的都认为允许还原路由 * @param {type} route * @return:boolean true-允许 false-禁止 */ shouldAttach(route: ActivatedRouteSnapshot): boolean { // 在路由是login的时候清空缓存 if(route.routeConfig['path'] === 'login'){ this._cacheRouters = {}; } return !!route.routeConfig && !!this._cacheRouters[route.routeConfig.path]; } /** * @description: 获取存储的路由 * 从缓存中获取快照 * @param {type} route * @return:若无则返回null */ retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { if (!route.routeConfig || !this._cacheRouters[route.routeConfig.path]) return null; return this._cacheRouters[route.routeConfig.path].handle; } /** * @description: 同一路由时,复用路由;进入路由触发 * @param {type} * @return:boolean true-复用 false-不复用 */ shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { return future.routeConfig === curr.routeConfig; } } | |
注册 | |
// 将策略注册到模块当中 providers: [ { provide: RouteReuseStrategy, useClass: SimpleReuseStrategy } ] | |
删除路由快照 | |
// 组件导入 providers: [SimpleReuseStrategy] module => 存储的key delete SimpleReuseStrategy._cacheRouters[module]; | |
懒加载情况下,复用策略失效; | |
| |
使用路由复用策略后ngOnInit 的方法不会再执行 | |
import {NavigationEnd, Router} from '@angular/router'; constructor(private router: Router) { this.router.events.filter((event) => event instanceof NavigationEnd).subscribe((event: NavigationEnd) => { // 这里需要判断一下当前路由,如果不加的话,每次路由结束的时候都会执行这里的方法,这里以search组件为例 if (event.url === '/search') {
this.search(); // 在这写需要执行初始化的方法 } }); } |
参考地址 | ||
Ng-Alain reuse-tab | https://github.com/ng-alain/delon/blob/master/packages/abc/reuse-tab/reuse-tab.service.ts | |
复杂路由复用策略 | https://github.com/angular/angular/issues/13869#issuecomment-441054267 |