0

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, it's just returning an array of observables.

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

How can I get this function to return data instead of observables?

1
  • 1
    You have to subscribe to get to send the request. Commented Oct 2, 2018 at 8:51

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

yeah I cant believe I didnt subscribe, I've done this a million times lol I guess I need some sleep
It happens with all of us. Take a break. Drink a coffee. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.