Вы должны использовать RouteReuseStrategy, как упомянуто здесь: https://itnext.io/cache-components-with-angular-routereusestrategy-3e4c8b174d5f
Создать службу cache-route-reuse.strategy.ts:
import { RouteReuseStrategy } from '@angular/router/';
import { ActivatedRouteSnapshot, DetachedRouteHandle } from '@angular/router';
export class CacheRouteReuseStrategy implements RouteReuseStrategy {
storedRouteHandles = new Map<string, DetachedRouteHandle>();
allowRetrieveCache = {
'mapbox': true
};
shouldReuseRoute(before: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
if (this.getPath(before) === 'the-path-of-the-first-component' && this.getPath(curr) === 'the-path-of-the-second-component') {
this.allowRetrieveCache['mapbox'] = true;
} else {
this.allowRetrieveCache['mapbox'] = false;
}
return before.routeConfig === curr.routeConfig;
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
return this.storedRouteHandles.get(this.getPath(route)) as DetachedRouteHandle;
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
const path = this.getPath(route);
if (this.allowRetrieveCache[path]) {
return this.storedRouteHandles.has(this.getPath(route));
}
return false;
}
shouldDetach(route: ActivatedRouteSnapshot): boolean {
const path = this.getPath(route);
if (this.allowRetrieveCache.hasOwnProperty(path)) {
return true;
}
return false;
}
store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {
this.storedRouteHandles.set(this.getPath(route), detachedTree);
}
private getPath(route: ActivatedRouteSnapshot): string {
if (route.routeConfig !== null && route.routeConfig.path !== null) {
return route.routeConfig.path;
}
return '';
}
}
И затем зарегистрировать ее в своемapp.module.ts:
...
providers: [{
provide: RouteReuseStrategy,
useClass: CacheRouteReuseStrategy
}],
...
Возможно, вы захотите адаптировать поведение метода shouldReuseRoute (например, я считаю, что он будет работать при переходе к map2 из map1, но не другим способом).