import {RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle} from '@angular/router';
export class CustomReuseStrategy implements RouteReuseStrategy {
handlers: {[key: string]: DetachedRouteHandle} = {};
shouldDetach(route: ActivatedRouteSnapshot): boolean {
//console.debug('CustomReuseStrategy:shouldDetach', route);
return !!route.data && !!(route.data as any).shouldDetach;
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
//console.debug('CustomReuseStrategy:store', route, handle);
this.handlers[route.routeConfig.path] = handle;
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
//console.debug('CustomReuseStrategy:shouldAttach', route);
return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
//console.debug('CustomReuseStrategy:retrieve', route);
if (!route.routeConfig) { return null; }
return this.handlers[route.routeConfig.path];
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
//console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr);
return future.routeConfig === curr.routeConfig;
}
}
第二步 - 在app.module中添加了CustomReuseStrategy提供程序。
import {RouteReuseStrategy} from '@angular/router';
import {CustomReuseStrategy} from './Shared/reuse-strategy';
providers: [
{ provide: RouteReuseStrategy, useClass: CustomReuseStrategy }
]
第三个 - 在 app.routing.ts 中添加了 shouldDetach 属性。
import { Routes, RouterModule } from "@angular/router";
import { MapComponent } from './components/map/map.component';
const ROUTES: Routes = [
{ path: 'maps', component: MapComponent , canActivate:[AuthGuard], data: { shouldDetach: true} },
];