应用场景
项目打开多个tab页面,在页面之间进行切换,应用路由复用策略:不用刷新页面,可以使用路由快照,保留了页面之前写入的内容。
理解说明
在angular官方文档中介绍:一种重新使用激活的路由的可自定义的方法。
abstract class RouteReuseStrategy {
abstract shouldDetach(route: ActivatedRouteSnapshot): boolean
abstract store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void
abstract shouldAttach(route: ActivatedRouteSnapshot): boolean
abstract retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null
abstract shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean
}
首先定义一个class,AppReuseStrategy继承RouteReuseStrategy。
主要流程调用顺序:
- shouldReuseRoute :确定是否应重用路由。相当于点击tab页,进入路由触发,比较futrue和curr是否为统一路由,返回true则不会进行跳转,false则跳转并调用其他方法。
public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig &&
JSON.stringify(future.params) === JSON.stringify(curr.params);
}
- shouldDetach:确定是否应分离此路由以便以后重用。离开页面时调用,会比落地页面的构造函数先执行。返回结果代表是否允许路由复用,true会执行store方法,false则表示你不想利用该路由,可以在方法内加上逻辑判断。
/** 表示对所有路由允许复用,如果有路由不想复用可以在这加一些业务逻辑判断 */
public shouldDetach(route: ActivatedRouteSnapshot): boolean {
return true;
}
- store:存储分离的路由。
public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
if (AppReuseStrategy.waitDelete && AppReuseStrategy.waitDelete === this.getRouteUrl(route)) {
// 如果待删除是当前路由则不存储快照
AppReuseStrategy.waitDelete = null;
return;
}
const anyhandle = handle as any;
if (anyhandle && anyhandle.route && anyhandle.route.children.length > 0) {
anyhandle.route = anyhandle.route.children[0];
}
AppReuseStrategy.handlers[this.getRouteUrl(route)] = anyhandle;
}
- shouldAttach:确定是否应该重新连接上(之前激活的)路由。返回true会调用retrieve方法。
/** 若 path 在缓存中有的都认为允许还原路由 */
public shouldAttach(route: ActivatedRouteSnapshot): boolean {
const flag = !!AppReuseStrategy.handlers[this.getRouteUrl(route)];
return flag;
}
- retrieve:检索之前存储的路由。
/** 从缓存中获取快照,若无则返回null */
public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { // 检索
if (!route.routeConfig) {
return null;
}
if (route.routeConfig.loadChildren) {
return null;
}
// return AppReuseStrategy.handlers[route.routeConfig.path];
return AppReuseStrategy.handlers[this.getRouteUrl(route)];
}
方法补充
public static handlers: { [key: string]: DetachedRouteHandle } = {};
private static waitDelete: string; // 当前页未进行存储时需要删除
public static deleteRouteSnapshot(name: string) {
// 删除路由快照 AppReuseStrategy.handlers数组内存储的就是路由快照
name = name.replace(/\//g, '_');
if (AppReuseStrategy.handlers[name]) {
delete AppReuseStrategy.handlers[name];
} else {
AppReuseStrategy.waitDelete = name;
}
}
private getRouteUrl(route: ActivatedRouteSnapshot) {
const result = route['_routerState'].url.replace(/\//g, '_');
return result;
}
参考文章:
https://segmentfault.com/a/1190000015391814?utm_source=tag-newest
https://blog.csdn.net/zgrbsbf/article/details/93304005