angular – 如何仅为特定路由激活RouteReuseStrategy
发布时间:2020-12-17 07:06:42 所属栏目:安全 来源:网络整理
导读:有没有办法只为特定路由实现RouteReuseStrategy? 这意味着每个路由都有子项,获得自己的RouteReuseStrategy自定义实现,并且只有在激活特定“树”中的路由时才触发其方法. 我目前使用的是this答案中的代码,但如果可能,我想用上面的逻辑扩展它. 解决方法 创建
有没有办法只为特定路由实现RouteReuseStrategy?
这意味着每个路由都有子项,获得自己的RouteReuseStrategy自定义实现,并且只有在激活特定“树”中的路由时才触发其方法. 我目前使用的是this答案中的代码,但如果可能,我想用上面的逻辑扩展它. 解决方法
创建自定义路由重用策略
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数组中实现新策略: providers: [ { provide: RouteReuseStrategy,useClass: CustomRouteReuseStategy },... ] 然后,声明所需的路由,并将数据属性“shouldReuse”设置为true { path: 'myPath',component: MyComponent,data: { shouldReuse: true } }, 只有具有data属性shouldReuse设置为true的路由才会被重用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |