可以创建一个 Map 来存储组件实例,使用自定义路由重用策略进行处理,并在销毁时调用其 ngOnDestroy 方法。
下面是示例代码:
import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';
export class CustomRouteReuseStrategy implements RouteReuseStrategy {
private handlers: Map = new Map();
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return true;
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
this.handlers.set(route.routeConfig.path, handle);
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
return this.handlers.has(route.routeConfig.path);
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
return this.handlers.get(route.routeConfig.path);
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig && JSON.stringify(future.params) === JSON.stringify(curr.params);
}
ngOnDestroy() {
for (let handle of this.handlers.values()) {
handle['componentRef'].instance.ngOnDestroy();
}
}
}
在上述代码中,我们创建了一个 handlers Map,它存储了路由路径和 DetachedRouteHandle 的键值对。该方案会在应用销毁时枚举存储的 DetachedRouteHandle,并在它的 componentRef 上调用 ngOnDestroy。
要使用该自定义路由重用策略,只需在 app.module 中进行注册:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, RouteReuseStrategy } from '@angular/router';
import { AppComponent } from './app.component';
import { CustomRouteReuseStrategy } from './custom-route-reuse-strategy';
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot([...]),
],
providers: [
{ provide: RouteReuseStrategy, useClass: CustomRouteReuseStrategy }
],
declarations: [
AppComponent,
],
bootstrap: [