如何处理 Angular Subsink 中的两个 api 调用?

How to handle two api calls in Angular Subsink?

我正在 angular subsink 内进行 api 调用,如下所示:

import {SubSink} from 'subsink';
...
...
async clickButton() {
    for (let i = 0; i < this.Id.length; i++) {
        const hostId = await this.serviceA.Status(this.hostName[i]);
        this.subs.sink = this.serviceB.createDbEntry(hostId))
            .subscribe(s => {
                if (i === this.Id.length - 1) {
                    this.dialog.close();
                }
            });
    }
}

这里this.Id的类型是any

现在我想在 this.serviceB.createDbEntry(hostId) 成功完成后进行另一个 api 调用 而且,我通过添加另一个 subs.subsink 来做到这一点,如下所示:

import {SubSink} from 'subsink';
...
...
async clickButton() {
    for (let i = 0; i < this.Id.length; i++) {
        const hostId = await this.serviceA.Status(this.hostName[i]);
        this.subs.sink = this.serviceB.createDbEntry(hostId))
            .subscribe(s => {
                if (i === this.Id.length - 1) {
                    this.dialog.close();
                }
            });
        this.subs.sink = this.serviceC.runRetry(hostId))
            .subscribe(s => {
                if (i === thisserverId.length - 1) {
                    this.dialog.close();
                }
            });             
    }
}

这是在 this.serviceB.createDbEntry(hostId)) 之后关闭对话框,而不是调用 this.serviceC.runRetry(hostId))

使用 Observables

您可以使用 RxjsforkJoinswitchMap 运算符。

检查 forkjoindocumentation 以及

检查 documentationswitchMap

通过使用运算符,您可以重写代码,例如

forkJoin(this.hostName.slice(0, this.Id.length).map(hostName => {
  return this.serviceA.Status(hostName).pipe(
    switchMap(hostId => this.serviceB.createDbEntry(hostId).pipe(map((dbEntry) => ({dbEntry, hostId})))),
    switchMap(resp => this.serviceC.runEntry(resp.hostId))
  )
})).subscribe(() => this.dialog.close());

使用 Promise

Promise.all(this.hostName.slice(0, this.Id.length).map(hostName => 
      this.serviceA.Status(hostName)
      .then(hostId => this.serviceB.createDbEntry(hostId).then(() => hostId))
      .then(hostId => this.serviceC.runEntry(hostId))
      )).then(() => this.dialog.close())