3

我已经花了至少 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/operators”中。Observable.combineLatest 也不起作用。

谢谢。

4

3 回答 3

5

使用 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));
于 2018-05-10T22:49:34.567 回答
1

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

t$ = combineLatest(
  this.route.params,
  this.route.queryParams
).pipe(
  map(results => ({params: results[0], queryParams: results[1]}))
);
于 2018-05-10T22:12:30.613 回答
0

我偶然发现了同样的问题,并且接受的答案很有效,但是如果您同时更改路由参数和查询参数,订阅将被触发两次。为了避免这种情况,我使用了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);
      });
于 2018-09-12T12:32:29.897 回答