【问题标题】:Angular 8 RXJS - Make multiple HTTP calls sequentiallyAngular 8 RXJS - 按顺序进行多个 HTTP 调用
【发布时间】:2020-01-09 11:48:16
【问题描述】:

我的代码是:

return this.creaClienti(cliente)
      .pipe(
        tap(res => console.log('Cliente ->', res)),
        concatMap(res => this.creaIntolleranza(intolleranza)),
        tap(res => console.log('Intolleranza ->', res)),
        concatMap(res => this.creaSpaziUtilizzati(utilizzoSpazi)),
        tap(res => console.log('Utilizzo spazi ->', res)),
        concatMap(res => this.creaEvento(evento))
      );
  }

但是 this.creaClienti(cliente) 是:

 creaClienti(clienti: any[]): Observable<any> {
    return from(clienti).pipe(
      concatMap(cliente => <Observable<any>>this.http.post(environment.baseUrl + 'api/json/node/cliente', cliente, this.httpOptions))
    );
  }

问题是每次包含的调用结束时管道都会重新启动...

我需要依次运行多个调用列表,concatMap中的所有函数其实都类似于creaClienti

【问题讨论】:

  • 听起来是对的。您可以附加shareReplay(),并且多个订阅不应触发源 Observable。
  • 我不希望每次在 creaClienti 中进行的调用都会再次启动管道。
  • 管道重新开始是什么意思?你在哪里订阅这些 observables? .subscribeaync 管道?

标签: angular request rxjs httpclient


【解决方案1】:

我猜你希望你的所有函数(this.creaClientithis.creaIntolleranzathis.creaSpaziUtilizzatithis.creaEvento(evento))只在所有内部 http 调用完成时发出一次。

如果例如creaClienti 应该只在所有内部调用完成后发出,您可以根据需要添加 lasttoArray

creaClienti(clienti: any[]): Observable<any> {
  return from(clienti).pipe(
    concatMap(cliente => <Observable<any>>this.http.post(environment.baseUrl + 'api/json/node/cliente', cliente, this.httpOptions)),
    last() // only emit the last http response
    // or toArray() // emit all http response in an array when the last one completed
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多