我有一个 Angular 组件需要响应应用于当前页面的路由参数更改。例如,也许我有路由 page/:id
,如果 :id
发生变化,我想通过重新加载组件的内容来响应。
使用 ActivatedRoute
的 paramMap
,这很容易。当我在 page/:id
路由上时,我可以更改 URL 中的 :id
并且应用程序会做出适当的响应。当我离开 page/:id
路由时,组件被销毁,并且没有发出任何参数更改。
但是,如果我对 @ngrx/router-store
尝试相同的方法,则会发出比我实际想要的更多的路由参数更改。我正在从到 导航的 route 获取路线参数。这似乎是因为路由器存储在我的组件被销毁之前发出。
我需要一种方式来表达“我只需要此页面的路由参数,一旦离开此页面,我需要您停止响应路由参数更改。”我认为这就像实现一个在我的 ngOnDestroy()
中完成的 takeUntil(unsubscriber$)
一样简单。但是,这不起作用,因为下一个参数发射发生在 ngOnDestroy()
被调用之前。
我想这种行为是设计使然,但我不确定如何克服我面临的问题。
我已经计算出 Stackblitz that demonstrates the issue .
使用 @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();
}
}
使用 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();
}
}
最佳答案
更改您的 navigation action timing通过传递给 StoreRouterConnectingModule.forRoot
的配置对象到 PostActivation
:
@NgModule({
imports: [
CommonModule,
...
StoreRouterConnectingModule.forRoot({
navigationActionTiming: NavigationActionTiming.PostActivation,
}),
],
})
关于angular - NgRx router-store 在离开当前页面时发出路由参数更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61010850/