import {ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy} from '@angular/router';
export class CustomReuseStrategy implements RouteReuseStrategy {
handlers: { [key: string]: DetachedRouteHandle } = {};
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return route.data.shouldReuse || false;
}
store(route: ActivatedRouteSnapshot, handle: {}): void {
if (route.data.shouldReuse && this.getUrl(route)) {
this.handlers[this.getUrl(route)] = handle;
}
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!this.handlers[this.getUrl(route)];
}
retrieve(route: ActivatedRouteSnapshot): any {
if (!this.getUrl(route)) {
return null;
}
return this.handlers[this.getUrl(route)];
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig && JSON.stringify(future.params) === JSON.stringify(curr.params);
}
getUrl(route: ActivatedRouteSnapshot) {
if (!route.parent.url.join('/') || !route.url.join('/')) {
return null;
}
let url = '';
if (route.parent.url.join('/')) {
url += route.parent.url.join('/') + '/';
}
if (route.url.join('/')) {
url += route.url.join('/');
}
return url === '' ? null : url;
}
}
和内部路由配置:
export const myRoute: Route = {
path: 'my',
component: MyComponent,
data: {
pageTitle: 'MY'
},
children: [
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full'
},
{
path: 'dashboard',
component: MyDashboardComponent,
data: {
shouldReuse: true
}
},
{
path: 'orders',
component: MyOrdersComponent,
data: {
shouldReuse: true
}
},
{
path: 'event/:id',
component: MyEventComponent,
data: {
shouldReuse: true
}
}
]
};