Angular/RxJs 6 - 组合路由参数和查询参数不再工作



我花了至少 2 个小时试图让版本 6 工作,但无济于事。我只是无法同时获得路由参数和查询参数。

这是与旧版本最接近的语法,但它只记录查询参数。

我想做的是将其包装在全局路由服务中,以便方法调用干净,如果发生任何其他更新,我可以在一个地方进行更改。

import {BehaviorSubject, combineLatest, Observable} from 'rxjs';
constructor(private router: Router, private route: ActivatedRoute)
// body of constructor left out

// Combine them both into a single observable
const urlParams: Observable<any> = combineLatest(
this.route.params,
this.route.queryParams,
(params, queryParams) => ({ ...params, ...queryParams})
);
urlParams.subscribe(x => console.log(x));

我还注意到,由于某种原因,combinedLatest 不在"rxjs/运算符"中。 Observable.combineLatest 也不起作用。

谢谢。

使用 rxjs6 时,没有更多的结果选择器,因此您需要改用"map"。有关迁移 rxjs 迁移指南的文档

import {BehaviorSubject, combineLatest, Observable} from 'rxjs';
import {map} from 'rxjs/operators'
const urlParams: Observable<any> =  combineLatest(
this.route.params,
this.route.queryParams
).pipe(
map(([params, queryParams]) => ({...params, ...queryParams}))
);
urlParams.subscribe(x => console.log(x));

> combineLatest 提供了一个数组格式的输出... 请尝试按如下方式使用

t$ = combineLatest(
this.route.params,
this.route.queryParams
).pipe(
map(results => ({params: results[0], queryParams: results[1]}))
);

我偶然发现了同样的问题,并且接受的答案有效,但是如果您同时更改路由参数和查询参数,订阅将被触发两次。 为了避免这种情况,我使用了distinctUntilChanged

combineLatest(
this.route.params.pipe(distinctUntilChanged(), takeUntil(this.ngUnsubscribe)),
this.route.queryParams.pipe(distinctUntilChanged(), takeUntil(this.ngUnsubscribe))
)
.pipe(map(([params, queryParams]) => ({params, queryParams})))
.subscribe(({params, queryParams}) => {
console.log(params, queryParams);
});

最新更新