Angular2 - 用RouteReuseStrategy暂存route状态

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

你可能感兴趣的:(Angular2 - 用RouteReuseStrategy暂存route状态)