How to activate RouteReuseStrategy only for specific routes

生来就可爱ヽ(ⅴ<●) 提交于 2020-12-29 03:06:10

问题


Is there a way to implement RouteReuseStrategy only for specific routes?

Meaning each route with children, getting its own custom implementation of RouteReuseStrategy, and whose methods only fire when a route in a specific 'tree' is activated.

I currently use the code from this answer, but I want to expand it with the above logic if possible.


回答1:


Create a custom route reuse strategy

import { RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle } from "@angular/router";

export class CustomRouteReuseStategy implements RouteReuseStrategy {

  handlers: { [key: string]: DetachedRouteHandle } = {};

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return route.data.shouldReuse || false;
  }

  store(route: ActivatedRouteSnapshot, handle: {}): void {
    if (route.data.shouldReuse) {
      this.handlers[route.routeConfig.path] = handle;
    }
  }

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
  }

  retrieve(route: ActivatedRouteSnapshot): {} {
    if (!route.routeConfig) return null;
    return this.handlers[route.routeConfig.path];
  }

  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return future.data.shouldReuse || false;
  }

}

In your router module, implement the new strategy in the providers array:

providers: [
  { provide: RouteReuseStrategy, useClass: CustomRouteReuseStategy },
  ...
]

Then, declare the desired route with a data property 'shouldReuse' set to true

{ path: 'myPath', component: MyComponent, data: { shouldReuse: true } },

Only the routes with the data property shouldReuse set to true will be reused.




回答2:


Yes, you can do this by writing your own RouteReuseStrategy (CustomReuseStrategy).

To black or white list routes, you can search for a data property which you can set in the router-module under the route and then choose to attach the component (to reuse it later), or not.

Helpful links to get you started:

  • https://github.com/manfredsteyer/angular-2-reuse-strategy-sample/blob/master/app/shared/router/custom-reuse-strategy.ts

  • https://medium.com/@juliapassynkova/angular-2-component-reuse-strategy-9f3ddfab23f5

  • How to implement RouteReuseStrategy shouldDetach for specific routes in Angular 2



来源:https://stackoverflow.com/questions/49155895/how-to-activate-routereusestrategy-only-for-specific-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!