Angular 依赖订阅使用 forkJoin 和代码块来修改数据

Angular dependent subscriptions using forkJoin with code block for modifying data

我的订阅取决于之前订阅的结果。 我正在使用 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.
});

我是否需要不同的 operator/syntax 来实现此目的,或者我是否可以修改此方法?

你没有return从你的 flatMap 中观察到一个 observable,return 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)
}

是否第一个函数 return 是一个可观察对象,第二个函数 return 是 void。

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

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

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