Angular路由复用策略RouteReuseStrategy(常用于实现Tab页签切换页面)

发布时间:2019-06-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Angular路由复用策略RouteReuseStrategy(常用于实现Tab页签切换页面)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

使用场景

路由切换时,使用快照。常应用在tab页签切换时,原页签页面的填写的信息状态保留。原理就是使用路由复用策略,在切换路由时,将路由的快照存放起来,下次再打开此路由时加载对应快照。

路由复用

新建RouteReuseStrategy

新建一个CustomReuseStrategy.ts 实现接口 RouteReuseStrategy
查看 RouteReuseStrategy 的 API 了解更多

import { RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle } 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];
        }
    }

    /** 表示对所有路由允许复用 如果你有路由不想利用可以在这加一些业务逻辑判断 */
    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        // console.debug('shouldDetach======>', route);
        return true;
    }

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

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

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

        return CustomReuseStrategy.handlers[this.getRouteUrl(route)];
    }

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

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

}

app.module.ts进行注册

import { NgModule } from '@angular/core';
import { RouteReuseStrategy } from '@angular/router';
import { AppComponent } from './app.component';
import { CustomReuseStrategy } from './CustomReuseStrategy';

@NgModule({
  declarations: [
    AppComponent
],
  imports: [
    // your imports
  ],
  providers: [
    { provide: RouteReuseStrategy, useClass: CustomReuseStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

以上基本实现了所有路由复用。

删除路由快照

但是,如果切换路由时,需要路由重载而不是快照。则需要实现以下代码,删除对应的快照。
在tab.component.ts定义删除快照方法,切换tab时进行路由加载前进行调用即可。

import { Component, OnInit } from '@angular/core';
import { CustomReuseStrategy } from '../r';

@Component({
  selector: 'tabpage',
  templateUrl: './tabpage.component.html',
  styleUrls: ['./tabpage.component.css'],
  providers: [CustomReuseStrategy]
})
export class TodoComponent implements OnInit{
  constructor() {}

  ngOnInit(): void {}

  changeTab() {
    // 删除快照
    this.deleteRouteSnapshot();
    // tab切换代码,路由跳转代码
    // ...
  }

  /** 路由加载前可手动删除路由快照,切换路由则不会使用快照 */
  deleteRouteSnapshot() {
    CustomReuseStrategy.deleteRouteSnapshot('/todolazy');
  }
}

懒加载的路由复用

以上写法,适用于普通路由、路由懒加载(lazy loading module)、子路由、子路由懒加载(lazy loading
module)。亲测可用
RouteReuseStrategy can working with lazy loading feature modules

问题

如果遇到 `Error: Cannot reattach ActivatedRouteSnapshot created from a
different route` 这个问题,可以参考 :

https://stackoverflow.com/que...

参考文章

http://www.cnblogs.com/lslgg/...
https://www.cnblogs.com/loves...
https://ng-alain.com/componen...

脚本宝典总结

以上是脚本宝典为你收集整理的Angular路由复用策略RouteReuseStrategy(常用于实现Tab页签切换页面)全部内容,希望文章能够帮你解决Angular路由复用策略RouteReuseStrategy(常用于实现Tab页签切换页面)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: