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: [
    {

相关内容

热门资讯

正版透视器玲珑透视器多功能AI... 正版透视器玲珑透视器多功能AI教程,玲珑总是真的有透视器教程1、实时玲珑透视辅助更新:用户可以随时随...
正版开挂天天摸麻将开挂多功能A... 正版开挂天天摸麻将开挂多功能AI工具,天天摸麻将果然是有开挂工具在进入天天摸麻将软件靠谱后,参与本局...
正版外挂星聚汇外挂多功能AI脚... 正版外挂星聚汇外挂多功能AI脚本,星聚汇确实有外挂脚本1、完成星聚汇有辅助插件,帮助玩家取得所有比赛...
正版开挂盛世开挂多功能AI软件... 正版开挂盛世开挂多功能AI软件,盛世一直真的有开挂软件盛世辅助器是一种具有地方特色的麻将游戏,要想赢...
正版外挂团团竞技外挂多功能AI... 正版外挂团团竞技外挂多功能AI工具,团团竞技确实是真的有外挂工具1、许多玩家不知道团团竞技辅助怎么退...
正版外挂趣玩娱乐外挂多功能AI... 正版外挂趣玩娱乐外挂多功能AI攻略,趣玩娱乐好像真的是有外挂攻略1、每一步都需要思考,不同水平的挑战...
正版辅助哥哥打大A辅助多功能A... 您好,哥哥打大A这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这...
正版外挂胡乐安庆麻将外挂多功能... 正版外挂胡乐安庆麻将外挂多功能AI攻略,胡乐安庆麻将一贯真的有外挂攻略1、金币登录送、破产送、升级送...
正版开挂川渝互娱开挂多功能AI... 正版开挂川渝互娱开挂多功能AI攻略,川渝互娱竟然是有开挂攻略1、进入到川渝互娱是否有挂之后,能看到左...
正版辅助器兴动互娱辅助器多功能... 正版辅助器兴动互娱辅助器多功能AI插件,兴动互娱竟然存在有辅助器插件1、在兴动互娱插件功能辅助器技巧...