angular5路由复用策略实现保存页面状态

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

/**
* 自定义路由复用策略
* */
export class CustomReuseStrategy implements RouteReuseStrategy {

  public static handlers: {[key: string]: DetachedRouteHandle} = {};

  /** 删除缓存路由快照的方法 */
  public static deleteRouteSnapshot(path: string): void {
    const name = path.replace(/\//g, '_');
    if (CustomReuseStrategy.handlers[name]) {
      delete CustomReuseStrategy.handlers[name];
    }
  }

  /** 从缓存中获取快照,若无则返回nul */
  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
    if (!CustomReuseStrategy.handlers[this.getRouteUrl(route)]) {
      return null;
    }
    return CustomReuseStrategy.handlers[this.getRouteUrl(route)];
  }

  /** 若 path 在缓存中有的都认为允许还原路由 */
  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return !!CustomReuseStrategy.handlers[this.getRouteUrl(route)];
  }

  /** 表示对所有路由允许复用 如果你有路由不想利用可以在这加一些业务逻辑判断 */
  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    if (route['_routerState'].url == '/index/personManage/personList') {
      return true;
    }
    return false;
  }

  /** 进入路由触发,判断是否同一路由 */
  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return future.routeConfig === curr.routeConfig &&
      JSON.stringify(future.params) === JSON.stringify(curr.params);
  }

  /** 当路由离开时会触发。按path作为key存储路由快照&组件当前实例对象 */
  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void {
    CustomReuseStrategy.handlers[this.getRouteUrl(route)] = handle;
  }

  /** 使用route的path作为快照的key */
  getRouteUrl(route: ActivatedRouteSnapshot) {
    const path = route['_routerState'].url.replace(/\//g, '_');
    return path;
  }

}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule} from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import {SelectivePreloadingStrategy} from './selective-preloading-strategy';
import {LocationStrategy, HashLocationStrategy, PathLocationStrategy} from '@angular/common';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {RouteReuseStrategy} from '@angular/router';
import {CustomReuseStrategy} from './CustomReuseStrategy';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,
  ],
  providers: [
    SelectivePreloadingStrategy,
    {provide: RouteReuseStrategy, useClass: CustomReuseStrategy},
    {
      provide: LocationStrategy,
      useClass: HashLocationStrategy
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

你可能感兴趣的:(angular)