如何仅为特定路线激活 RouteReuseStrategy [英] How to activate RouteReuseStrategy only for specific routes
问题描述
有没有办法只为特定路线实现 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屋!