Angular2 版本2.3之后提供了一個實驗性的class: RouteReuseStrategy
可以用于暫存路由的狀態,在重新跳轉回該路由時恢復狀態(不用重新初始化component)。
定義:
class RouteReuseStrategy {
[shouldDetach
](https://angular.io/docs/ts/latest/api/router/index/RouteReuseStrategy-class.html#shouldDetach-anchor)(route: ActivatedRouteSnapshot) : boolean
[store
](https://angular.io/docs/ts/latest/api/router/index/RouteReuseStrategy-class.html#store-anchor)(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle) : void
[shouldAttach
](https://angular.io/docs/ts/latest/api/router/index/RouteReuseStrategy-class.html#shouldAttach-anchor)(route: ActivatedRouteSnapshot) : boolean
[retrieve
](https://angular.io/docs/ts/latest/api/router/index/RouteReuseStrategy-class.html#retrieve-anchor)(route: ActivatedRouteSnapshot) : DetachedRouteHandle
[shouldReuseRoute
](https://angular.io/docs/ts/latest/api/router/index/RouteReuseStrategy-class.html#shouldReuseRoute-anchor)(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot) : boolean
}
說明
shouldDetach(route: ActivatedRouteSnapshot) : boolean
決定是否將當前的路由進行分離并暫存。
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle) : void
存儲分離出的路由
shouldAttach(route: ActivatedRouteSnapshot) : boolean
決定當前的路由是否還原
retrieve(route: ActivatedRouteSnapshot) : DetachedRouteHandle
取得之前暫存的路由
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot) : boolean
決定是否重用路由
案例
export class CustomReuseStrategy implements RouteReuseStrategy {
handlers: {[key: string]: DetachedRouteHandle} = {};
shouldDetach(route: ActivatedRouteSnapshot): boolean {
console.debug('CustomReuseStrategy:shouldDetach', route);
return true;
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
console.debug('CustomReuseStrategy:store', route, handle);
this.handlers[route.routeConfig.path] = handle;
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
console.debug('CustomReuseStrategy:shouldAttach', route);
return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
console.debug('CustomReuseStrategy:retrieve', route);
return this.handlers[route.routeConfig.path];//從暫存處取回
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
//在此處可以取得跳轉前和跳轉后的路由路徑
console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr);
return future.routeConfig === curr.routeConfig;
}
}
Reference:
https://angular.io/docs/ts/latest/api/router/index/RouteReuseStrategy-class.html
https://www.softwarearchitekt.at/post/2016/12/02/sticky-routes-in-angular-2-3-with-routereusestrategy.aspx