简体   繁体   中英

Get data from http call inside for loop. Angular 2+

Hello I want to call my http request inside a for loop because I only want to execute 1000 items at a time. So I have the following code:

getData(IDs: string[]): Observable<any> {
    // IDs is a large array of strings, about 3000 of them

    const results = [];
    const totalData = [];

    // split the IDs array into chunks of 1000
    while (IDs.length) {
      results.push(IDs.splice(0, 1000));
    }

    // loop through the new array with the chunks of 1000 and run the http request
    for (let i = 0; i < results.length; i++) {
      const data = this.http.get(`myhttprequest/${results[i]}`);

      totalData.push(data);
    }

    console.log(totalData); 
    // this is just an array of observables when I am looking for an array of data

    return totalData
}

I'm not getting any errors, but instead of returning an array data, its just returning an array of observables.

I know its because the variables are updating before the data is returned so I've tried using promises and unfortunately I cant get that to work.

Can anyone help me to get this function to return data instead of observables?

Thanks!

Always subscribe!

An HttpClient method does not begin its HTTP request until you call subscribe() on the observable returned by that method. This is true for all HttpClient methods.

Reference link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM