在Angular 13中,我有一个路由,用于评估查询参数、路径参数和片段。每当导航到路线时,任何数量的参数都会发生变化,我都希望在一个单独的事件中处理所有的变化。
目前,为路线注册的组件使用combineLatest
:将参数组合为一个可观察的参数
ngOnInit(): void {
combineLatest([
this.route.params,
this.route.queryParams,
this.route.fragment
])
.pipe(map(p => {
return {
id: p[0]['id'], // path parameter 'id'
filter: p[1]['filter'], // query parameter 'filter'
section: p[2] // fragment
};
}))
.subscribe(p => {
// handle parameter update
// fetch data from backend
});
}
当使用routerLink
指令从路由(id=1,section=undefined(导航到路由(id=2,section=1(时,订阅中的代码会执行两次-第一次是针对片段中的更改(id=1,section=undefine(-->(id=1,section=1(和第二次改变id(id=2,section=1(-->(id=2,section=1(。
Barney在评论中提出的解决方案有效:将debounceTime(0)
包括在map
中解决了该问题。
ngOnInit(): void {
combineLatest([
this.route.params,
this.route.queryParams,
this.route.fragment
])
.pipe(
map(p => {
return {
id: p[0]['id'], // path parameter 'id'
filter: p[1]['filter'], // query parameter 'filter'
section: p[2] // fragment
};
}),
debounceTime(0) // <--- SOLUTION !!!
)
.subscribe(p => {
// handle parameter update
// fetch data from backend
});
}