【问题标题】:Angular dependent subscriptions using forkJoin with code block for modifying data使用 forkJoin 和代码块修改数据的 Angular 依赖订阅
【发布时间】:2019-08-25 12:27:22
【问题描述】:

我的订阅取决于之前订阅的结果。 我正在使用 forkJoin,所以我不必嵌套它们:

this.service.service1().pipe(
    flatMap((res1) => this.service.service2(res1))
).subscribe((res2) => {
    // Do something with res2.
});

问题是我需要在调用订阅 #2 之前修改数据。我希望能够做这样的事情:

this.service.service1().pipe(
    flatMap((res1) => {
      // Modify res1 data here.
      // Make 2nd Api Call
      this.service.service2(res1)
    })
).subscribe((res2) => {
    // Do something with res2.
});

我是否需要不同的运算符/语法来实现这一点,或者我可以修改这种方法吗?

【问题讨论】:

  • 您可以在flatMap 之前使用map 以使其更明显,但如果您不想返回res1,我认为您现在正在做的很好。
  • @martin 上面的第二个代码块是不可能的。 flatMap 不允许使用 {}。它将抛出 Type 'void' is not assignable to type 'ObservableInput' 错误。

标签: angular typescript rxjs subscription


【解决方案1】:

你没有从你的 flatMap 返回一个 observable,返回 this.service.service2(res1);将执行以下相同操作。

this.service.service1().pipe(
    map(res1 => //modify resp1 here)
    flatMap((modifiedRes1) => this.service.service2(modifiedRes1)) // note the lack of brackets, this means we are returning the observable, your function returns void.
).subscribe((res2) => {
    // Do something with res2.
});

两者的区别

(res1) => this.service.service2(res1)

(res1) => {
  this.service.service2(res1)
}

是不是第一个函数返回observable,第二个返回void。

(res1) => this.service.service2(res1)

(res1) => {
  return this.service.service2(res1)
}

是等价的。 {} 创建一个块,如果在箭头函数中使用该块,则需要一个 return 语句。

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 2020-03-29
    • 2021-11-19
    • 2020-10-17
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 2014-08-18
    相关资源
    最近更新 更多