使用 Angular RouteReuseStrategy 緩存(路由)組件
使用 Angular RouteReuseStrategy 緩存組件
Cache components with Angular RouteReuseStrategy
RouteReuseStrategy provider 允許我們控制 Angular 路由和組件生命周期的行為。
當(dāng)我們?cè)诮M件間切換的時(shí)候,Angular都會(huì)銷(xiāo)毀上一個(gè)組件,并且創(chuàng)建一個(gè)新的組件。在大多數(shù)情況下,我們可能不想讓它這樣工作,因?yàn)槊看渭虞d一個(gè)組件,可能會(huì)有很多類(lèi)似HTTP請(qǐng)求一樣的昂貴的操作。
這時(shí)候就需要RouteReuseStrategy了。
RouteReuseStrategy是什么
RouteReuseStrategy接口聲明了5個(gè)方法。
shouldReuseRoute
這個(gè)方法每次切換路由時(shí)都會(huì)被調(diào)用。future參數(shù)是將要離開(kāi)的路由,curr參數(shù)是將要加載的路由。如果這個(gè)方法返回true,路由將不會(huì)跳轉(zhuǎn)(意味著路由沒(méi)有發(fā)生變化)。如果它返回false,則路由發(fā)生變化并且其余方法會(huì)被調(diào)用。
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
// 默認(rèn)行為
return future.routeConfig === curr.routeConfig;
}
shouldAttach
路由剛剛被打開(kāi),當(dāng)我們加載到這個(gè)路由的組件上時(shí),shouldAttach會(huì)被調(diào)用。一旦組件被加載這個(gè)方法都會(huì)被調(diào)用。如果這個(gè)方法返回true,retrieve方法將會(huì)被調(diào)用。否則這個(gè)組件將會(huì)被重新創(chuàng)建。
shouldAttach(route: ActivatedRouteSnapshot): boolean;
retrieve
當(dāng)shouldAttach方法返回true時(shí)這個(gè)方法會(huì)被調(diào)用。提供當(dāng)前路由的參數(shù)(剛打開(kāi)的路由),并且返回一個(gè)緩存的RouteHandle。如果返回null表示沒(méi)有效果。我們可以使用這個(gè)方法手動(dòng)獲取任何已被緩存的RouteHandle。框架不會(huì)自動(dòng)管理它,需要我們手動(dòng)實(shí)現(xiàn)。
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null;
shouldDetach
當(dāng)離開(kāi)當(dāng)前路由時(shí)這個(gè)方法會(huì)被調(diào)用。如果返回true,store方法會(huì)被調(diào)用。
shouldDetach(route: ActivatedRouteSnapshot): boolean;
store
這個(gè)方法當(dāng)且僅當(dāng)shouldDetach方法返回true時(shí)被調(diào)用。我們可以在這里具體實(shí)現(xiàn)如何緩存RouteHandle。在這個(gè)方法中緩存的內(nèi)容將會(huì)被用在retrieve方法中。它提供了我們離開(kāi)的路由和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];
}
}
/**
* 判斷當(dāng)前路由是否需要緩存
* 這個(gè)方法返回false時(shí)則路由發(fā)生變化并且其余方法會(huì)被調(diào)用
* @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);
}
/**
* 當(dāng)離開(kāi)當(dāng)前路由時(shí)這個(gè)方法會(huì)被調(diào)用
* 如果返回 true 則 store 方法會(huì)被調(diào)用
* @param {ActivatedRouteSnapshot} route
* @returns {boolean}
* @memberof CacheRouteReuseStrategy
*/
public shouldDetach(route: ActivatedRouteSnapshot): boolean {
return true;
}
/**
* 將路由寫(xiě)入緩存
* 在這里具體實(shí)現(xiàn)如何緩存 RouteHandle
* 提供了我們離開(kāi)的路由和 RouteHandle
* @param {ActivatedRouteSnapshot} route
* @param {DetachedRouteHandle} detachedTree
* @memberof CacheRouteReuseStrategy
*/
public store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {
RouteStrategyService.handlers[this.getPath(route)] = detachedTree;
}
/**
* 路由被導(dǎo)航 如果此方法返回 true 則觸發(fā) retrieve 方法
* 如果返回 false 這個(gè)組件將會(huì)被重新創(chuàng)建
* @param {ActivatedRouteSnapshot} route
* @returns {boolean}
* @memberof CacheRouteReuseStrategy
*/
public shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!RouteStrategyService.handlers[this.getPath(route)];
}
/**
* 從緩存讀取cached route
* 提供當(dāng)前路由的參數(shù)(剛打開(kāi)的路由),并且返回一個(gè)緩存的 RouteHandle
* 可以使用這個(gè)方法手動(dòng)獲取任何已被緩存的 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 { }
以上示例運(yùn)行時(shí)會(huì)緩存所有路由組件。
實(shí)現(xiàn)比如標(biāo)簽頁(yè)效果時(shí),關(guān)閉標(biāo)簽頁(yè),調(diào)用RouteStrategyService中的deleteRouteSnapshot方法刪除已緩存的頁(yè)面即可。
這里可能會(huì)有個(gè)問(wèn)題,如果你不想用這個(gè)路由緩存了,請(qǐng)務(wù)必刪除掉app.module.ts中的providers,而不是將RouteStrategyService的shouldReuseRoute始終return true;這樣會(huì)出現(xiàn)路由跳轉(zhuǎn)頁(yè)面不跳轉(zhuǎn)的問(wèn)題,原因暫時(shí)未知。
以下是運(yùn)行效果圖:

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

當(dāng)我們?cè)诮M件間切換的時(shí)候,Angular都會(huì)銷(xiāo)毀上一個(gè)組件,并且創(chuàng)建一個(gè)新的組件。在大多數(shù)情況下,我們可能不想讓它這樣工作,因?yàn)槊看渭虞d一個(gè)組件,可能會(huì)有很多類(lèi)似HTTP請(qǐng)求一樣的昂貴的操作。
這時(shí)候就需要RouteReuseStrategy了。
浙公網(wǎng)安備 33010602011771號(hào)