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 { }

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

相关内容

热门资讯

此事迅速冲上热搜!wepoke... 此事迅速冲上热搜!wepoker数据分析(透视)衢州都莱辅助软件(确实存在有辅助辅助器)-哔哩哔哩该...
据悉!黑侠破解wepoker(... 据悉!黑侠破解wepoker(透视)新星游辅助真的假的(一直有辅助软件)-哔哩哔哩1、新星游辅助真的...
今年以来!pokemomo辅助... 今年以来!pokemomo辅助工具(透视)河南微乐小程序辅助器免费(切实存在有辅助app)-哔哩哔哩...
透视智能ai!哈糖大菠萝怎么挂... 透视智能ai!哈糖大菠萝怎么挂(透视)烧饼游戏修改器(真是是真的辅助平台)-哔哩哔哩1、每一步都需要...
透视实锤!wepoker免费脚... 透视实锤!wepoker免费脚本咨询(透视)小南娱乐外g挂系统(原来是有辅助下载)-哔哩哔哩1)小南...
据统计!wepoker怎么挂飞... 据统计!wepoker怎么挂飞机(透视)创思维激k怎么开挂(其实真的有辅助app)-哔哩哔哩1、完成...
据权威媒体报道!we-poke... 据权威媒体报道!we-poker辅助(透视)手机奇迹辅助工具(一贯真的有辅助安装)-哔哩哔哩所有人都...
今天上午!wpk有作必弊吗(透... 今天上午!wpk有作必弊吗(透视)超凡辅助下载(一贯有辅助插件)-哔哩哔哩运超凡辅助下载辅助工具,进...
透视透视挂!wpk辅助购买(透... 透视透视挂!wpk辅助购买(透视)h5能反杀吗(原来有辅助安装)-哔哩哔哩亲,关键说明,h5能反杀吗...
现就发布提示!红龙poker辅... 现就发布提示!红龙poker辅助平台(透视)微乐家乡自建房辅助app(原来存在有辅助app)-哔哩哔...