要解决这个问题,需要在应用程序中实现自定义的RouteReuseStrategy。使用自定义的RouteReuseStrategy可让我们决定在路由时是否应重复使用组件实例。我们可以使用RouteReuseStrategy接口中的shouldDetach,store,shouldAttach和retrieve方法将路由元数据存储在内存中,并在下次访问该路由时重新使用它们。
以下是解决此问题的代码示例:
import {RouteReuseStrategy, DetachedRouteHandle} from '@angular/router';
export class CustomRouteReuseStrategy extends RouteReuseStrategy {
private handlers: {[key: string]: DetachedRouteHandle} = {};
shouldDetach(route: import("@angular/router").ActivatedRouteSnapshot): boolean {
return !!route.data.reuse;
}
store(route: import("@angular/router").ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
this.handlers[route.url.join('/')] = handle;
}
shouldAttach(route: import("@angular/router").ActivatedRouteSnapshot): boolean {
return !!this.handlers[route.url.join('/')];
}
retrieve(route: import("@angular/router").ActivatedRouteSnapshot): DetachedRouteHandle {
if (!route.routeConfig || route.routeConfig.loadChildren || !this.handlers[route.url.join('/')]) {
return null;
}
return this.handlers[route.url.join('/')];
}
shouldReuseRoute(future: import("@angular/router").ActivatedRouteSnapshot, curr: import("@angular/router").ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
}
}
在应用程序的模块中,只需将CustomRouteReuseStrategy添加到providers数组中即可:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, RouteReuseStrategy } from '@angular/router';
import { CustomRouteReuseStrategy } from './custom-route-reuse-strategy';
@NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
providers: [
{