import { RouteReuseStrategy, DefaultUrlSerializer, ActivatedRouteSnapshot, DetachedRouteHandle, Route } from '@angular/router';
import { ComponentRef } from '@angular/core';
export class SimpleReuseStrategy implements RouteReuseStrategy {
public static handlers: Map<Route, DetachedRouteHandle> = new Map();
private getRouteUrl(route?: ActivatedRouteSnapshot | any) {
return route['_routerState'].url.replace(/[\/, -]/g, '_')
}
public shouldDetach(_route: ActivatedRouteSnapshot): boolean {
return true;
}
/** 当路由离开时会触发。按path作为key存储路由快照&组件当前实例对象 */
public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
if (!route.routeConfig) return;
SimpleReuseStrategy.handlers.set(route.routeConfig, handle);
}
/** 若 path 在缓存中有的都认为允许还原路由 */
public shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!route.routeConfig && !!SimpleReuseStrategy.handlers.get(route.routeConfig);
}
/** 从缓存中获取快照,若无则返回nul */
public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
if (!route.routeConfig || !SimpleReuseStrategy.handlers.has(route.routeConfig)) return null;
return SimpleReuseStrategy.handlers.get(route.routeConfig)!;
}
/** 进入路由触发,判断是否同一路由 */
public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
}
/** 清除缓存 */
public clearCacheHandle() {
SimpleReuseStrategy.handlers.forEach(item => {
this.deactivateOutlet(item);
});
}
/** 处理同一组件不同链接的问题 */
private deactivateOutlet(handle?: DetachedRouteHandle | any): void | null {
const componentRef: ComponentRef<any> = handle ? handle['componentRef'] : null;
if (componentRef) {
componentRef.destroy();
}
}
/**
* 清除单个路由
* @param url
*/
public clearCacheByUrl(url: string) {
var route = url.substring(url.lastIndexOf('/') + 1);
SimpleReuseStrategy.handlers.forEach((value: DetachedRouteHandle, key: Route) => {
if (route == key.path) {
SimpleReuseStrategy.handlers.delete(key);
}
});
}
/**清除所有 */
public clearCacheAll() {
console.log("clearCacheAll");
SimpleReuseStrategy.handlers.clear();
}
/**保留一个 */
public clearCacheLeftOne(url: string) {
console.log("clearCacheLeftOne");
var route = url.substring(url.lastIndexOf('/') + 1);
SimpleReuseStrategy.handlers.forEach((value: DetachedRouteHandle, key: Route) => {
if (route!= key.path) {
SimpleReuseStrategy.handlers.delete(key);
}
});
}
/**
* 清除多个
* @param url
*/
public clearCacheByUrls(urlAry: Array<string>) {
console.log("clearCacheByUrls");
if (urlAry && urlAry.length > 0) {
let handleUrlAry: Array<string> = [];
urlAry.forEach(url => {
const handleUrl = url.substring(url.lastIndexOf('/') + 1);
handleUrlAry.push(handleUrl);
});
SimpleReuseStrategy.handlers.forEach((value: DetachedRouteHandle, key: Route) => {
if (key.path&&handleUrlAry.indexOf(key.path)>-1) {
SimpleReuseStrategy.handlers.delete(key);
}
});
}
}
}