如何仅针对特定路线激活 RouteReuseStrategy [英] How to activate RouteReuseStrategy only for specific routes

查看:39
本文介绍了如何仅针对特定路线激活 RouteReuseStrategy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法只为特定路由实现 RouteReuseStrategy?

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

意思是每条路线都有孩子,获得自己的 RouteReuseStrategy 自定义实现,并且其方法仅在特定树"中的路线被激活时触发.

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.

我目前使用 this 答案,但如果可能的话,我想用上述逻辑对其进行扩展.

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

推荐答案

创建自定义路由重用策略

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;
  }

}

在您的路由器模块中,在 providers 数组中实现新策略:

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

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

然后,声明所需的路由,并将数据属性shouldReuse"设置为 true

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

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

只有数据属性 shouldReuse 设置为 true 的路由才会被重用.

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

这篇关于如何仅针对特定路线激活 RouteReuseStrategy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆