【问题标题】:How to properly handle the angular route subscription and then use the parameters for parallel http requests如何正确处理角度路由订阅,然后将参数用于并行 http 请求
【发布时间】:2019-08-09 08:16:53
【问题描述】:

我尝试为以下场景找到合适的解决方案:

我从订阅路由参数中得到了一个 Observable。现在,如果此订阅触发它应该启动两个并行的 http 请求。

我尝试将 switchMap 与 forkJoin 结合使用。可悲的是,这没有奏效。以下代码有效,但我认为我不应该在订阅中使用订阅?那么正确的解决方案是什么?

this.subscriptions.add(this.route.params.subscribe( params => {
   this.subscriptions.add(forkJoin(
     [this.componentService.getComponentDetails( params.id ), this.planService.getPlanTypes()]
   ).subscribe(
     (data) => {
       console.log(data);
     },
     (error) => {
       console.error('Error loading Form: ', error);
     }
   ));
}));

订阅对象随后用于取消订阅 (ngOnDestroy)。

【问题讨论】:

  • 您预期的最终结果是什么?你见过 Rxjs 的 Zip 吗?
  • 我刚刚在上面的示例中登录的数据用于填充下拉选项和其他内容......我期望的是一个适合该场景的解决方案:httpCall1 -> parallel( httpCall2(使用结果httpCall1), httpCall3) -> 处理来自 httpCalls 2 和 3 的数据。
  • 如果你想在 httpCall2 中使用 httpCall1 的输出...你的意思是串行的。并行意味着你想同时执行所有的请求……对吧?

标签: angular rxjs


【解决方案1】:

嵌套订阅是一种反模式。您可以使用 switchMap 运算符重构代码以返回单个订阅。

const sub = this.route.paramMap
  .pipe(switchMap(paramMap => {
    const id = paramMap.get('id');
    return forkJoin([
      this.componentService.getComponentDetails(id), 
      this.planService.getPlanTypes()
    ])
  })).subscribe(data => console.log(data))

this.subscriptions.add(sub)

另外,请注意我是如何使用 paramMap 而不是 params。这是在最新版本的 Angular 中访问参数的首选方式。

【讨论】:

  • 实际上我尝试了类似的方法但出现错误。我不知道为什么会出现该错误以及与您的解决方案有什么区别,但是您的解决方案有效。非常感谢。
  • 乐于助人:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多