Angular自定义路由重用策略在存储的组件上调用ngOnDestroy方法?
创始人
2024-11-01 11:00:36
0

可以创建一个 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: [

相关内容

热门资讯

推荐透视!wepoker私人局... 推荐透视!wepoker私人局透视方法,wepoker如何设置透视,都是真的是有辅助软件(哔哩哔哩)...
有挂透视!aapoker辅助插... 有挂透视!aapoker辅助插件工具,aapoker怎么提高中牌率,确实存在有辅助教程(哔哩哔哩)1...
普及透视!hhpoker怎么防... 普及透视!hhpoker怎么防作比弊,hhpoker辅助挂是真的吗,都是存在有辅助软件(哔哩哔哩)透...
揭露透视!wpk俱乐部是做什么... 揭露透视!wpk俱乐部是做什么的,wpk插件辅助,果然真的是有辅助教程(哔哩哔哩)辅助器是一种具有地...
透视透视!aapoker辅助插... 透视透视!aapoker辅助插件工具,aapoker怎么选牌,其实存在有辅助神器(哔哩哔哩)透视方法...
揭露透视!aapoker怎么拿... 揭露透视!aapoker怎么拿好牌,aapoker插件,都是是真的有辅助方法(哔哩哔哩)1、操作简单...
详细透视!aapoker安装包... 详细透视!aapoker安装包怎么使用,aapoker安装包怎么使用,果然一直都是有辅助软件(哔哩哔...
教你透视!德普之星私人局辅助免... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...
必备透视!wepoker免费脚... 必备透视!wepoker免费脚本咨询,wepoker私局代打,其实一直总是有辅助攻略(哔哩哔哩)1、...
详细透视!wepoker辅助器... 详细透视!wepoker辅助器安装包,wepoker有没有挂,确实是有辅助脚本(哔哩哔哩)1、辅助软...