Angular的RouteReuseStrategy与LazyLoadedModule搭配使用时,在路由到另一个模块后,MainLayout没有消失且[routerLinks]不起作用
创始人
2024-10-24 09:31:04
0

要解决这个问题,需要在应用程序中实现自定义的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: [
    {

相关内容

热门资讯

发现玩家!老k游戏辅助,hhp... 发现玩家!老k游戏辅助,hhpoker外挂靠谱吗,新2025版(有挂透视)是一款可以让一直输的玩家,...
分享一款!新超凡大厅辅助,hh... 分享一款!新超凡大厅辅助,hhpoker可以控制吗,切实教程(有挂辅助);1、在新超凡大厅辅助ai机...
程序员教你!微信辅助工具,哈糖... 程序员教你!微信辅助工具,哈糖大菠萝攻略,细节方法(真的有挂);1、这是跨平台的微信辅助工具黑科技,...
一分钟了解!广东雀神挂件脚本开... 一分钟了解!广东雀神挂件脚本开挂,pokemmo辅助脚本,wpk教程(有挂分享);【福星临门,好运相...
大神推荐!广西老友玩游戏辅助器... 大神推荐!广西老友玩游戏辅助器,微扑克辅助,新2025版(有挂透视);一、广西老友玩游戏辅助器AI软...
必备教程!科乐天天踢辅助视频,... 必备教程!科乐天天踢辅助视频,来玩app破解,详细教程(的确有挂);科乐天天踢辅助视频软件透明挂作为...
盘点一款!凑一桌开挂,wepo... 盘点一款!凑一桌开挂,wepoker透视底牌,透明挂教程(有挂透视);1、超多福利:超高返利,海量正...
玩家交流!518互游辅助,we... 玩家交流!518互游辅助,wepoker新号好一点吗,我来教教你(有挂攻略);最新版2026是一款经...
重大通报!贪玩互娱辅助,wej... 重大通报!贪玩互娱辅助,wejoker内置辅助,科技教程(有挂规律);贪玩互娱辅助软件透明挂更新新赛...
必备攻略!汇城辅助,wepok... 必备攻略!汇城辅助,wepoker怎么看牌型,2025新版总结(有挂秘诀);详细汇城辅助攻略(汇城辅...