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

相关内容

热门资讯

分享认知!wepoker轻量版... 分享认知!wepoker轻量版有透视吗,德普之星有透视辅助吗,确实真的有挂(真的有挂)1、透视辅助软...
六分钟了解!德扑圈透视,wep... 六分钟了解!德扑圈透视,wepoker辅助器安装包定制,都是是真的有挂(有挂细节)一、wepoker...
大家学习交流!wepoker插... 大家学习交流!wepoker插件辅助,竞技联盟破解版最新版,原来存在有挂(有挂攻略)1、玩家可以在线...
技术分享!hhpoker德州机... 技术分享!hhpoker德州机器人,aapoker辅助怎么用,总是有挂(有挂攻略)1、每一步都需要思...
一分钟了解!竞技联盟透视,hh... 一分钟了解!竞技联盟透视,hhpoker怎么开透视,好像存在有挂(有挂细节)一、游戏安装教程牌型概率...
玩家必备教程!sohoo po... 玩家必备教程!sohoo poker辅助,hhpoker作弊码怎么用,确实真的是有挂(有挂详情)一、...
热点推荐!哈糖大菠萝攻略,红龙... 热点推荐!哈糖大菠萝攻略,红龙poker作弊指令,果然真的有挂(有挂存在)1、免费脚本咨询教程、免费...
指导大家!pokermaste... 指导大家!pokermaster脚本,德普辅助app,本来是真的有挂(有挂方法)1、完成辅助器v3....
科技通报!aapoker透视怎... 科技通报!aapoker透视怎么用,wejoker私人辅助软件,都是真的有挂(有挂攻略)1、这是跨平...
一分钟教会你!hhpoker智... 一分钟教会你!hhpoker智能辅助插件,hhpoker免费透视脚本,一直真的是有挂(有挂头条)1、...