通过路由重用来管理订阅

时间:2017-07-05 05:57:45

标签: angular angular-routing

假设我有一个组件,订阅发生在onInit并取消订阅onDestroy

ngOnInit(){
  // subscribe
}

ngOnDestroy() {
  // unsubscribe
}

但现在正在转向自定义路由重用策略,其中组件将被重用。我的问题是如何管理这些订阅,以便在我导航回组件的路径时不会调用onInit onDestroy

如何在用户离开路线(组件)时取消订阅并在导航回路线(组件)时订阅?

Angular 4.1.1 angular-cli 1.0.1

希望我简单明了。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。您可以使用RouteReuseStrategy store方法来实现自定义的附加/分离组件生命周期挂钩。

如果附加了ActivatedRouteSnapshot,则store方法将null作为detachedRouteHandle接收到DetachedRouteHandles (空=附加,值=分离)

我使用组件作为路由键和服务来存储export class SelectiveRouteReuseStrategy implements RouteReuseStrategy { constructor( private detachedRouteHandlesService: DetachedRouteHandlesService, ) { } public shouldDetach(route: ActivatedRouteSnapshot): boolean { return !!route.data.reuse; } public store(route: ActivatedRouteSnapshot, detachedRouteHandle: DetachedRouteHandle): void { detachedRouteHandle ? this.detachedRouteHandlesService.set(route.component, detachedRouteHandle) : this.detachedRouteHandlesService.delete(route.component); } public shouldAttach(route: ActivatedRouteSnapshot): boolean { return !!route.data.reuse ? this.detachedRouteHandlesService.has(route.component) : false; } public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null { return !!route.data.reuse ? this.detachedRouteHandlesService.get(route.component) : null; } public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { return future.routeConfig === curr.routeConfig; } }

RouteReuse策略代码:

DetachedRouteHandlesService

store具有Map属性-DetachedRouteHandle,其组件为键,changes为值;和Observable属性-export class DetachedRouteHandlesService { private readonly store: Map<any, DetachedRouteHandle>; private readonly changes: Subject<Map<any, DetachedRouteHandle>>; public readonly changes$: Observable<Map<any, DetachedRouteHandle>>; constructor() { this.store = new Map(); this.changes = new Subject(); this.changes$ = this.changes.asObservable(); } private next(): void { this.changes.next(this.store); } public set(component: any, handle: DetachedRouteHandle): void { this.store.set(component, handle); this.next(); } public delete(component: any): void { this.store.delete(component); this.next(); } public get(component: any): DetachedRouteHandle | null { return this.store.get(component); } public has(component: any): boolean { return this.store.has(component); } public clear(): void { this.store.clear(); this.next(); } } 用于根据商店更改发出商店。

DetachedRouteHandlesService代码:

DetachedRouteHandle

在组件中,只需订阅更改并选中ngOnInit() { this.detachedRouteHandlesService.changes$ .pipe( observeOn(asapScheduler) ).subscribe(changes => { changes.has(this.activatedRoute.component) ? this.onDetach() : this.onAttach() }); } 具有手柄=已分离,否则=已连接

组件代码:

List<>