0

I want to to get data for several different ProductIds from an remote source using httpClient within an angular service. I want to combine the data within the service and then return it.

Using just one productId, this works just fine:

getData(productId: string): Observable<any> {
  const path = this.serverUrl + '?' + 'productId=' + productId;
  return this.httpClient.get(path);
}

But how can I iterate over an array of product Ids and then return the combined result?

getData(productIds: Array<string>): Observable<any> {
  let data: Array<string>;

  productIds.forEach(element => {
     const path = this.serverUrl + '?' + 'productid=' + element;
     data.push(this.httpClient.get(path));
  });

  return data;

}

Thanks for your help!

1
  • 1
    Me personally I'd create a REST endpoint on the server to which you can post the array of IDs so a single HTTP call (and probably a single database query) can return all the products necessary... Like this it is very performance intensive. Commented Mar 8, 2019 at 10:59

3 Answers 3

2

If you want to ask for different products in parallel you can use forkJoin operator:

getData(productIds: Array<string>): Observable<any> {  
  const data = productIds.map(element => {
     const path = this.serverUrl + '?' + 'productid=' + element;
     return this.httpClient.get(path);
  };
  return forkJoin(...data);
}

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

Comments

1

you can try using forkJoin

[P.S.] the code below is not tested

 let productAPIs = [1,2,3,4];

 productIds.forEach(element => {
    const path = this.serverUrl + '?' + 'productid=' + element;
    productAPIs.push(this.http.get(path);
 });


 forkJoin(productAPIs).subscribe(results => {
    // results[0] is your productId[0]
    // results[1] is your productId[1]
 });

Comments

0

You should take a look at the zip function from RXJS. It combines all the results from different observables into an array.

getData(productIds: Array<string>): Observable<any> {
  let data: Array<Observable<any>>;

  productIds.forEach(element => {
     const path = this.serverUrl + '?' + 'productid=' + element;
     data.push(this.httpClient.get(path));
  });

  return zip(data);
}

Comments

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.