关于在tabset中动态加载Component ,点击查看我之前的文章
介绍了如何使用动态加载Component 的方式实现tabset 标签页,从而达到页面切换。
这种方式缺点就是无法使用Angular 的路由来跳转,多个页面如果如果某个元素的id 值相同会有影响。
以下的方式主要使用了Angular 的路由复用功能—>RouteReuseStrategy
主要借鉴了 ng-alian里面的delon
https://github.com/ng-alain/delon
Angular在官网上显示是一个实验性的功能
解释
具体来说就是重写上述的5个方法
主要代码
route-reuse-strategy.ts
export class CustomeRouteReuseStrategy implements RouteReuseStrategy {
constructor(private reuseTabService: ReuseTabService) {
}
/** 表示对所有路由允许复用 如果你有路由不想利用可以在这加一些业务逻辑判断 */
public shouldDetach(route: ActivatedRouteSnapshot): boolean {
return this.reuseTabService.shouldDetach(route);
}
/** 当路由离开时会触发。按path作为key存储路由快照&组件当前实例对象 */
public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
return this.reuseTabService.store(route, handle);
}
/** 若 path 在缓存中有的都认为允许还原路由 */
public shouldAttach(route: ActivatedRouteSnapshot): boolean {
return this.reuseTabService.shouldAttach(route);
}
/** 从缓存中获取快照,若无则返回null */
public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
return this.reuseTabService.retrieve(route);
}
/** 进入路由触发,判断是否同一路由 */
public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return this.reuseTabService.shouldReuseRoute(future,curr);
}
}
reuse-tab-service.ts
import {
Injectable, OnDestroy, Injector } from '@angular/core';
import {
ActivatedRouteSnapshot, ActivatedRoute } from '@angular/router';
import {
ReuseTabCached, ReuseTabNotify } from '../models/reuse-tab';
import {
BehaviorSubject, Observable } from 'rxjs';
import {
filter } from 'rxjs/operators';
@Injectable()
export class ReuseTabService implements OnDestroy {
private _cachedChange: BehaviorSubject<ReuseTabNotify> = new BehaviorSubject<ReuseTabNotify>(null);
/**缓存路由列表 */
private _reuseTabCachedList: ReuseTabCached[] = [];
private _titleCached: {
[url: string]: string } = {
};
private removeUrlBuffer: string;
/** 当前路由地址 */
get curUrl() {
return this.getUrl(this.injector.get(ActivatedRoute).snapshot);
}
/** 获取已