Angular 8 make multiple http requests and combine all results

17,399

Solution 1

your code is correct since that is the expected behavior of forkjoin you just need to map it a little bit

forkJoin([res1, res2, res3, res4, res5])
.pipe(map(data => data.reduce((result,arr)=>[...result,...arr],[])))
.subscribe(data =>{

  this.autoCompleteValues = data;
  console.log(this.autoCompleteValues);
});

Solution 2

Instead of this:

forkJoin([res1, res2]).subscribe((data) => {
    console.log(data)
});

Do this:

forkJoin([res1, res2]).subscribe(([data1, data2]) => {
    console.log(data1)
    console.log(data2)
});
Share:
17,399
khansen
Author by

khansen

Updated on June 15, 2022

Comments

  • khansen
    khansen almost 2 years

    I am trying to use forkJoin to perform multiple http get requests and then combine all results into a simple Array using Angular 8.

    The problem is that I end up with an Array of Arrays... instead of one Array of strings

    My code below. All endpoints return a list of strings.

    autoCompleteValues: any;
    
    ngOnInit() {
    
        let res1 = this.dataMessageService.getFoo1();
        let res2 = this.dataMessageService.getFoo2();
        let res3 = this.dataMessageService.getFoo3();
        let res4 = this.dataMessageService.getFoo4();
        let res5 = this.dataMessageService.getFoo5();
    
        forkJoin([res1, res2, res3, res4, res5]).subscribe(data => {
    
          this.autoCompleteValues = data;
          console.log(this.autoCompleteValues);
        });
    }
    

    What am I doing wrong? How can I combine all the results into one large Array?