Luca_
Luca_

Reputation: 13

Angular 8 RXJS - Make multiple HTTP calls sequentially

My code is:

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))
      );
  }

but this.creaClienti(cliente) is:

 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))
    );
  }

the problem is that every time a contained call is ended the pipe restarts...

I need to run multiple call lists sequentially, all the functions that are in the concatMap are in fact similar to creaClienti

Upvotes: 1

Views: 1206

Answers (1)

frido
frido

Reputation: 14139

I guess you want all your functions (this.creaClienti, this.creaIntolleranza, this.creaSpaziUtilizzati, this.creaEvento(evento)) to only emit once when all inner http calls completed.

If e.g. creaClienti should only emit once all internal calls are done you can add last or toArray depending on the output you want.

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
  );
}

Upvotes: 1

Related Questions