Jos*_*eel 5 rxjs ngrx angular ngrx-router-store
我有一个 Angular 组件需要响应应用于当前页面的路由参数更改。例如,也许我有路线page/:id,如果发生:id变化,我想通过重新加载组件的内容来响应。
使用ActivatedRoute's paramMap,这很容易。当我在page/:id路线上时,我可以更改:idURL 中的 ,应用程序会做出适当的响应。当我离开路线时page/:id,组件将被销毁,并且不会发出任何参数更改。
但是,如果我尝试使用相同的方法@ngrx/router-store,则会发出比我实际想要的更多的路由参数更改。我从正在导航到的路线获取路线参数。这似乎发生是因为路由器存储在我的组件被销毁之前发出。
我需要一种方式来表达“我只想要此页面的路由参数,并且一旦导航离开此页面,我需要您停止响应路由参数更改。” 我认为这就像takeUntil(unsubscriber$)在我的ngOnDestroy(). 但是,这不起作用,因为下一个参数发射发生在ngOnDestroy()调用之前。
我想这种行为是设计使然,但我不确定如何克服我面临的问题。
我已经制定了一个Stackblitz 来演示这个问题。
使用 来处理这种情况最优雅的方法是什么@ngrx/router-store?
工作示例使用ActivatedRoute
export class MyComponent implements OnInit, OnDestroy {
unsubscriber$ = new Subject<void>();
constructor(public route: ActivatedRoute) {}
ngOnInit() {
this.route.paramMap
.pipe(takeUntil(this.unsubscriber$))
.subscribe(params => {
// reload data
});
}
ngOnDestroy() {
this.unsubscriber$.next();
this.unsubscriber$.complete();
}
}
Run Code Online (Sandbox Code Playgroud)
使用非工作示例router-store
export class MyComponent implements OnInit, OnDestroy {
unsubscriber$ = new Subject<void>();
constructor(public store: Store<State>) {}
ngOnInit() {
this.store
.pipe(select(selectRouteParams), takeUntil(this.unsubscriber$))
.subscribe(params => {
// reload data
// this code is being run even when this component is being navigated away from
});
}
ngOnDestroy() {
this.unsubscriber$.next();
this.unsubscriber$.complete();
}
}
Run Code Online (Sandbox Code Playgroud)
通过传入的配置对象更改导航操作时间:PostActivationStoreRouterConnectingModule.forRoot
@NgModule({
imports: [
CommonModule,
...
StoreRouterConnectingModule.forRoot({
navigationActionTiming: NavigationActionTiming.PostActivation,
}),
],
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1809 次 |
| 最近记录: |