Angular 2+浏览器后退按钮不重新加载子路由。
创始人
2024-10-15 15:30:09
0

在Angular 2+中,可以通过使用RouteReuseStrategy来解决浏览器后退按钮不重新加载子路由的问题。下面是一个代码示例:

首先,创建一个自定义的路由重用策略类,例如CustomReuseStrategy

import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';

export class CustomReuseStrategy implements RouteReuseStrategy {
  private handlers: { [key: string]: DetachedRouteHandle } = {};

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return false;
  }

  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void {
    this.handlers[route.routeConfig?.path as string] = handle as DetachedRouteHandle;
  }

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return !!route.routeConfig && !!this.handlers[route.routeConfig.path as string];
  }

  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
    if (!route.routeConfig) return null;
    return this.handlers[route.routeConfig.path as string] || null;
  }

  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return future.routeConfig === curr.routeConfig;
  }
}

接下来,在你的AppModule中使用这个自定义的路由重用策略类:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, RouteReuseStrategy } from '@angular/router';

import { AppComponent } from './app.component';
import { CustomReuseStrategy } from './custom-reuse-strategy';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, RouterModule.forRoot([...])],
  providers: [{ provide: RouteReuseStrategy, useClass: CustomReuseStrategy }],
  bootstrap: [AppComponent]
})
export class AppModule { }

通过这样配置之后,当用户点击浏览器的后退按钮时,子路由将不会重新加载,而是会复用之前的组件实例。

相关内容

热门资讯

玩家亲测!pokemomo辅助... 玩家亲测!pokemomo辅助工具,wepoker有没有机器人,可靠技巧(有挂软件)1、不需要AI权...
科普常识!wejoker辅助软... 科普常识!wejoker辅助软件视频,hhpoker开挂教程,新版2025教程(有挂透明);致您一封...
记者揭秘!pokemmo辅助官... 《记者揭秘!pokemmo辅助官网,约局吧辅助器,曝光教程(有挂透明)》 pokemmo辅助官网软件...
科技分享!大菠萝789辅助器下... 1、科技分享!大菠萝789辅助器下载,wepoker可以开透视吗,必胜教程(有挂技巧)。2、大菠萝7...
重要通知!newpoker怎么... 重要通知!newpoker怎么安装脚本,wpk透视是真的假的,扑克教程(有挂透视);《WPK辅助透视...
一分钟教你!wpk免费辅助,a... 一分钟教你!wpk免费辅助,aapoker辅助工具安全吗,微扑克教程(有挂攻略),支持语音通讯、好友...
玩家必备攻略!wepoker轻... 玩家必备攻略!wepoker轻量版书签,wepoker辅助器如何使用,专业教程(有挂教程)准备好在w...
盘点几款!wepoker私人局... 盘点几款!wepoker私人局俱乐部怎么进,佛手大菠萝辅助,爆料教程(有挂软件)1、玩家可以在wep...
一分钟了解!线上德州的辅助器是... 一分钟了解!线上德州的辅助器是什么,pokemomo辅助软件,AI教程(有挂攻略)1、不需要AI权限...
玩家交流!poker worl... 玩家交流!poker world辅助器,wepoker网页版透视方法,大神讲解(有挂软件)是一款可以...