user1034912
user1034912

Reputation: 2257

How do I make multiple Rxjs http calls sequentially and access all results in subscribe?

I have 3 http requests

let a: Observable<string> = this.dataService.getData1();
let b: Observable<number> = this.dataService.getData2();
let c: Observable<boolean> = this.dataService.getData3();

I want to call getData1, getData2, and getData3 sequentially (one after the other) and return all data in a single subscribe.

{
    //What do I put here?
}.subscribe(data => {
    //I have the result of all 3 data (string,number, and boolean)
}, error => {
    //If one data fails, it throws an error
});

Upvotes: 0

Views: 31

Answers (1)

Fan Cheung
Fan Cheung

Reputation: 11345

With concat and reduce or toArray, you can get all results in one emission in subscribe()

concat(
  a,
  b,
  c
).pipe(reduce((acc, curr) => [curr, ...acc], []))
  .subscribe(console.log);

concat(
  a,
  b,
  c
).pipe(toArray())
  .subscribe(console.log);

Upvotes: 2

Related Questions