来自 技术 2019-03-06 00:00 的文章

angular 路由复用和路由懒加载

浪费了“黄金五年”的Java程序员,还有救吗?>>>

1. 注入 { provide: RouteReuseStrategy, useClass: SimpleReuseStrategy },

2.

import {ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy} from '@angular/router';

//页面缓存用的

export class SimpleReuseStrategy implements RouteReuseStrategy {

public static handlers: { [key: string]: DetachedRouteHandle } = {}

private static waitDelete:string

/** 表示对所有路由允许复用 如果你有路由不想利用可以在这加一些业务逻辑判断 */

public shouldDetach(route: ActivatedRouteSnapshot): boolean {

return true;

}

/** 当路由离开时会触发。按path作为key存储路由快照&组件当前实例对象 */

public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {

if(SimpleReuseStrategy.waitDelete && SimpleReuseStrategy.waitDelete==this.getRouteUrl(route)){

//如果待删除是当前路由则不存储快照

SimpleReuseStrategy.waitDelete=null

return;

}

SimpleReuseStrategy.handlers[this.getRouteUrl(route)] = handle

}

/** 若 path 在缓存中有的都认为允许还原路由 */

public shouldAttach(route: ActivatedRouteSnapshot): boolean {

return !!SimpleReuseStrategy.handlers[this.getRouteUrl(route)]

}

/** 从缓存中获取快照,若无则返回nul */

public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {

if (!route.routeConfig) {

return null

}

return SimpleReuseStrategy.handlers[this.getRouteUrl(route)]

}

/** 进入路由触发,判断是否同一路由 */

public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {

return future.routeConfig===curr.routeConfig &&

JSON.stringify(future.params)==JSON.stringify(curr.params);

}

private getRouteUrl(route: ActivatedRouteSnapshot){

return route['_routerState'].url.replace(/\//g, '_');

//+ '_' + (route.routeConfig.loadChildren || route.routeConfig.component.toString().split('(')[0].split(' ')[1] )

}

public static deleteRouteSnapshot(name:string):void{

if(SimpleReuseStrategy.handlers)

if(SimpleReuseStrategy.handlers[name]){

delete SimpleReuseStrategy.handlers[name];

}else{

SimpleReuseStrategy.waitDelete=name;

}

} 

public static deleteRouteSnapshot2(name:string):void{

if(SimpleReuseStrategy.handlers[name]){

delete SimpleReuseStrategy.handlers[name];

}else{

SimpleReuseStrategy.waitDelete=name;

}

}

}