使用 Angular RouteReuseStrategy 緩存(路由)組件


使用 Angular RouteReuseStrategy 緩存組件

Cache components with Angular RouteReuseStrategy

RouteReuseStrategy provider 允許我們控制 Angular 路由和組件生命周期的行為。

當我們在組件間切換的時候,Angular都會銷毀上一個組件,並且創建一個新的組件。在大多數情況下,我們可能不想讓它這樣工作,因為每次加載一個組件,可能會有很多類似HTTP請求一樣的昂貴的操作。

這時候就需要RouteReuseStrategy了。

RouteReuseStrategy是什么

RouteReuseStrategy接口聲明了5個方法。

shouldReuseRoute

這個方法每次切換路由時都會被調用。future參數是將要離開的路由,curr參數是將要加載的路由。如果這個方法返回true,路由將不會跳轉(意味着路由沒有發生變化)。如果它返回false,則路由發生變化並且其余方法會被調用。

shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    // 默認行為
    return future.routeConfig === curr.routeConfig;
}

shouldAttach

路由剛剛被打開,當我們加載到這個路由的組件上時,shouldAttach會被調用。一旦組件被加載這個方法都會被調用。如果這個方法返回trueretrieve方法將會被調用。否則這個組件將會被重新創建。

shouldAttach(route: ActivatedRouteSnapshot): boolean;

retrieve

shouldAttach方法返回true時這個方法會被調用。提供當前路由的參數(剛打開的路由),並且返回一個緩存的RouteHandle。如果返回null表示沒有效果。我們可以使用這個方法手動獲取任何已被緩存的RouteHandle。框架不會自動管理它,需要我們手動實現。

retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null;

shouldDetach

當離開當前路由時這個方法會被調用。如果返回truestore方法會被調用。

shouldDetach(route: ActivatedRouteSnapshot): boolean;

store

這個方法當且僅當shouldDetach方法返回true時被調用。我們可以在這里具體實現如何緩存RouteHandle。在這個方法中緩存的內容將會被用在retrieve方法中。它提供了我們離開的路由和RouteHandle

store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void;

示例

src/services/route-strategy.service.ts:


import { RouteReuseStrategy, DetachedRouteHandle, ActivatedRouteSnapshot } from '@angular/router';
export class RouteStrategyService implements RouteReuseStrategy {
  public static handlers: { [key: string]: DetachedRouteHandle } = {};
  public static deleteRouteSnapshot(path: string): void {
    const name = path.replace(/\//g, '_');
    if (RouteStrategyService.handlers[name]) {
      delete RouteStrategyService.handlers[name];
    }
  }
  /**
   * 判斷當前路由是否需要緩存
   * 這個方法返回false時則路由發生變化並且其余方法會被調用
   * @param {ActivatedRouteSnapshot} future
   * @param {ActivatedRouteSnapshot} curr
   * @returns {boolean}
   * @memberof CacheRouteReuseStrategy
   */
  public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return future.routeConfig === curr.routeConfig
      && JSON.stringify(future.params) === JSON.stringify(curr.params);
  }
  /**
   * 當離開當前路由時這個方法會被調用
   * 如果返回 true 則 store 方法會被調用
   * @param {ActivatedRouteSnapshot} route
   * @returns {boolean}
   * @memberof CacheRouteReuseStrategy
   */
  public shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return true;
  }
  /**
   * 將路由寫入緩存
   * 在這里具體實現如何緩存 RouteHandle
   * 提供了我們離開的路由和 RouteHandle
   * @param {ActivatedRouteSnapshot} route
   * @param {DetachedRouteHandle} detachedTree
   * @memberof CacheRouteReuseStrategy
   */
  public store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {
    RouteStrategyService.handlers[this.getPath(route)] = detachedTree;
  }
  /**
   * 路由被導航 如果此方法返回 true 則觸發 retrieve 方法
   * 如果返回 false 這個組件將會被重新創建
   * @param {ActivatedRouteSnapshot} route
   * @returns {boolean}
   * @memberof CacheRouteReuseStrategy
   */
  public shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return !!RouteStrategyService.handlers[this.getPath(route)];
  }
  /**
   * 從緩存讀取cached route
   * 提供當前路由的參數(剛打開的路由),並且返回一個緩存的 RouteHandle
   * 可以使用這個方法手動獲取任何已被緩存的 RouteHandle
   * @param {ActivatedRouteSnapshot} route
   * @returns {(DetachedRouteHandle | null)}
   * @memberof CacheRouteReuseStrategy
   */
  public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
    return RouteStrategyService.handlers[this.getPath(route)] || null;
  }
  private getPath(route: ActivatedRouteSnapshot): string {
    // tslint:disable-next-line: no-string-literal
    const path = route['_routerState'].url.replace(/\//g, '_');
    return path;
  }
}

src/app/app.module.ts:

import { RouteReuseStrategy } from '@angular/router';
import { RouteStrategyService } from '../services/route-strategy.service';

@NgModule({
    ...
    providers: [
        ...
        { provide: RouteReuseStrategy, useClass: RouteStrategyService }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

以上示例運行時會緩存所有路由組件。
實現比如標簽頁效果時,關閉標簽頁,調用RouteStrategyService中的deleteRouteSnapshot方法刪除已緩存的頁面即可。

這里可能會有個問題,如果你不想用這個路由緩存了,請務必刪除掉app.module.ts中的providers,而不是將RouteStrategyServiceshouldReuseRoute始終return true;這樣會出現路由跳轉頁面不跳轉的問題,原因暫時未知。

以下是運行效果圖:

The end...
Last updated by Jehorn, 11/1/2019


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM