如何仅为特定路线激活 RouteReuseStrategy
How to activate RouteReuseStrategy only for specific routes
有没有办法只对特定路由实施RouteReuseStrategy
?
意味着每条路线都有子路线,获得自己的 RouteReuseStrategy
自定义实现,并且其方法仅在特定 'tree' 中的路线被激活时触发。
我目前使用 答案中的代码,但如果可能的话,我想用上述逻辑对其进行扩展。
创建自定义路由重用策略
import { RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle } from "@angular/router";
export class CustomRouteReuseStrategy 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
数组中实施新策略:
providers: [
{ provide: RouteReuseStrategy, useClass: CustomRouteReuseStategy },
...
]
然后,将数据 属性 'shouldReuse' 设置为 true
来声明所需的路由
{ path: 'myPath', component: MyComponent, data: { shouldReuse: true } },
只有数据 属性 shouldReuse
设置为 true
的路由才会被重用。
是的,您可以通过编写自己的 RouteReuseStrategy (CustomReuseStrategy) 来做到这一点。
对于黑名单或者白名单路由,可以在路由下的router-module中搜索一个数据属性可以设置,然后选择附加组件(以后复用) , 与否。
帮助您入门的有用链接:
有没有办法只对特定路由实施RouteReuseStrategy
?
意味着每条路线都有子路线,获得自己的 RouteReuseStrategy
自定义实现,并且其方法仅在特定 'tree' 中的路线被激活时触发。
我目前使用
创建自定义路由重用策略
import { RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle } from "@angular/router";
export class CustomRouteReuseStrategy 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
数组中实施新策略:
providers: [
{ provide: RouteReuseStrategy, useClass: CustomRouteReuseStategy },
...
]
然后,将数据 属性 'shouldReuse' 设置为 true
来声明所需的路由{ path: 'myPath', component: MyComponent, data: { shouldReuse: true } },
只有数据 属性 shouldReuse
设置为 true
的路由才会被重用。
是的,您可以通过编写自己的 RouteReuseStrategy (CustomReuseStrategy) 来做到这一点。
对于黑名单或者白名单路由,可以在路由下的router-module中搜索一个数据属性可以设置,然后选择附加组件(以后复用) , 与否。
帮助您入门的有用链接: