从角度queryParams只获取最终值

时间:2019-12-12 08:26:14

标签: angular rxjs angular-routing

我的目标是确定在加载应用程序时是否设置了查询参数project。同时我还必须加载项目列表。当我同时获得这两种信息时,就可以继续我的逻辑了。

这是我到目前为止所得到的

combineLatest([
  this.route.queryParams.pipe(pluck('project')),
  this.projects$.pipe(first(),filter(p => p && p.length > 0))
]).subscribe(([projectParam, projects]) => {
  console.log(projectParam, projects);
});

this.route的类型为ActivatedRoute:https://angular.io/api/router/ActivatedRoute

可观察的项目$理想。但是queryParams可观察到的被调用了两次。一次使用值undefined,然后再使用实际值。但是我只想要最后一个值。 由于网址是可选的,所以两个选项都有效。

任何想法都可以使queryParams触发最终值。

5 个答案:

答案 0 :(得分:0)

尝试使用最后一个rxjs运算符

this.route.queryParams.pipe(last(), pluck('project'))

答案 1 :(得分:0)

this.route.queryParams在内部实现为从未完成的主题,但是您希望它在与undefined不同的第一个值之后立即完成。

因此,您可以将takeWhile与可选的第二个参数一起使用:

this.route.queryParams.pipe(
  takeWhile(val => val === undefined, true), // or maybe !Boolean(val)
  takeLast(1),
  pluck('project')),
)

或者仅使用filter()take(1)可能会更容易。

答案 2 :(得分:0)

您可以使用跳过运算符跳过第一个。

 combineLatest([
      this.route.queryParams.pipe(pluck('project')),
      this.projects$.pipe(first(),filter(p => p && p.length > 0))
    ]).pipe(skip(1)).subscribe(([projectParam, projects]) => {
      console.log(projectParam, projects);
    });

答案 3 :(得分:0)

为什么不能简单地订阅route.queryParams并检查它是否具有project参数。

这是我完成任务的想法。

ngOnInit() {
    this.route.queryParams.subscribe(queryParams => {
        if (queryParams.project) {
            // proceed with your logic
        }
    });
}

答案 4 :(得分:0)

感谢此处的讨论:https://github.com/angular/angular/issues/12157 我想出了以下解决方案:

private get finalQueryParams$(): Observable<Params> {
  return merge(
    // get urls with query params like /test?project=test
    this.route.queryParams.pipe(
      filter(params => Object.keys(params).length > 0)
    ),
    // get urls without query params like /test
    this.route.queryParams.pipe(
      filter(() => !(window.location.href || '').includes('?')),
      map(() => ({}))
    )
  );
}

它只触发一次,我得到了queryParams的真实价值。

在上面的代码中,我只需要将其更改为

combineLatest([
  this.finalQueryParams$.pipe(pluck('project')),
  this.projects$.pipe(first(),filter(p => p && p.length > 0))
]).subscribe(([projectParam, projects]) => {
  console.log(projectParam, projects);
});
相关问题