Angular 当导航离开当前页面时,NgRx路由器存储发出路由参数更改
我有一个角度组件,需要响应应用于当前页面的路由参数更改。例如,可能我有路由Angular 当导航离开当前页面时,NgRx路由器存储发出路由参数更改,angular,rxjs,ngrx,ngrx-router-store,Angular,Rxjs,Ngrx,Ngrx Router Store,我有一个角度组件,需要响应应用于当前页面的路由参数更改。例如,可能我有路由页面/:id,如果:id发生更改,我希望通过重新加载组件的内容来响应 使用ActivatedRoute的paramMap,这很简单。当我在页面/:id路径上时,我可以更改URL中的:id,应用程序会做出相应的响应。当我离开页面/:id路径时,组件被销毁,并且不会发出任何参数更改 但是,如果我对@ngrx/router store尝试相同的方法,将发出比我实际需要的更多的路由参数更改。我正在从正在导航到的路由获取路由参数。这
页面/:id
,如果:id
发生更改,我希望通过重新加载组件的内容来响应
使用ActivatedRoute
的paramMap
,这很简单。当我在页面/:id
路径上时,我可以更改URL中的:id
,应用程序会做出相应的响应。当我离开页面/:id
路径时,组件被销毁,并且不会发出任何参数更改
但是,如果我对@ngrx/router store
尝试相同的方法,将发出比我实际需要的更多的路由参数更改。我正在从正在导航到的路由获取路由参数。这似乎是因为路由器存储在我的组件被破坏之前发出了信号
我需要一种方式来表示“我只想要这个页面的路由参数,一旦这个页面被导航到别处,我需要你停止响应路由参数的更改。”我想这就像实现一个takeUntil(unsubscriber$)
一样简单,它在我的ngondstroy()
中完成。但是,这不起作用,因为下一个参数是在调用ngondstroy()
之前发出的
我想这种行为是故意的,但我不知道如何克服我所面临的问题
我已经制定了一个计划
使用@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();
}
}
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();
}
}
通过传递到StoreRouterConnectionModule的配置对象,将您的设置更改为PostActivation
。对于root
:
@NgModule({
进口:[
公共模块,
...
StoreRouterConnectionModule.forRoot({
navigationActionTiming:navigationActionTiming.PostActivation,
}),
],
})