0

I have a GET request that I need to make. The thing is that each request only returns a page of 50 data entries so there can be multiple pages of data that can only be retrieved with different requests. I have to wait for all the data to be grabbed so that I can then process the data as a whole

I need to do something like"

for(var i = 1; i <= numPages; ++i){
     this.http.get(url, httpOptions).subscribe((information: any =>{
           allInfo.push(information);
        });
}
processData(allInfo);

where the url will be updated with the correct page.

I know that a processData will execute before the for loop finishes. Is there someway to incorporate promise and then statements or maybe a pipe to get all the data pushed to the allInfo array so that it can then be processed?

1 Answers1

2

One way would be that instead of subscribing to all HTTP requests, you store those observable in an array and then use forkJoin to subscribe to the combined result of all of them.

Something like this:

let observaleArray: Observable[] = [];

for(var i = 1; i <= numPages; ++i){
    observableArray.push(this.http.get(url, httpOptions));
}

forkJoin(observableArray)
    .subscribe(allInfo => {
       processData(allInfo); 
    });

Don't forget to import Observable and forkJoin.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
asimhashmi
  • 4,258
  • 1
  • 14
  • 34