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、这是跨平台的轻量版有...
推荐几款新版!德普之星辅助器怎... 推荐几款新版!德普之星辅助器怎么用(辅助挂)都是有挂(存在有挂辅助插件)辅助器是一种具有地方特色的麻...
一分钟揭秘!拱趴大菠萝挂怎么安... 一分钟揭秘!拱趴大菠萝挂怎么安装(辅助挂)原来是真的有挂(有挂教学辅助工具)在进入软件靠谱后,参与本...
玩家必备教程!wepoker辅... 玩家必备教程!wepoker辅助软件价格(辅助挂)其实是真的有挂(讲解有挂辅助软件)1、实时透视辅助...
揭秘几款!hhpoker智能辅... 揭秘几款!hhpoker智能辅助插件(辅助挂)总是是真的有挂(真是有挂辅助器)破解侠是真的助透视。每...
记者发布!pokemmo辅助工... 记者发布!pokemmo辅助工具(辅助挂)都是真的有挂(确实有挂辅助教程);1、点击下载安装,脚本分...
总算明白!pokemmo修改器... 总算明白!pokemmo修改器手机版(辅助挂)其实存在有挂(有挂细节辅助软件)1、任何透视是真的假的...
揭秘关于!wepoker私人局... 揭秘关于!wepoker私人局俱乐部怎么进(辅助挂)其实是真的有挂(有挂功能辅助器)1、每一步都需要...
分享一款!哈糖大菠萝攻略(辅助... 分享一款!哈糖大菠萝攻略(辅助挂)竟然是真的有挂(今日头条辅助插件)1、实时透视辅助更新:用户可以随...
一起来探讨!wejoker辅助... 一起来探讨!wejoker辅助脚本(辅助挂)切实真的有挂(有挂教程辅助软件)1、任何透视是真的假的的...