Search code examples
angularhttpodata

How to make a web request for multiple items in an array


I have created a page using Angular 5 where users select items and fire an ODATA web request that gets data for the items.

This is the code that currently works for one item.

  getqr(ID) {
   this.http.get("https://test.com/_api/web/lists/getbytitle('Document Separator Barcodes')/items?$orderBy=ID&$filter=ID eq '"+ ID +"'").subscribe(data => {
      console.log("data", data);
      console.log("data.value", data['value']);
      this.barcodeitems = data['value'];
    });
  }

I am storing all the selected items in an array but want the web request to filter based on all IDs in the array.

For two items it should be:

this.http.get("https://test.com/_api/web/lists/getbytitle('Document Separator Barcodes')/items?$orderBy=ID&$filter=ID eq '"+ ID +"' or ID eq '"+ID2 +"'"

and so on.

How could I do this?


Solution

  • Use map & join with string templating :

    // build filter query based on list of items
    let filterQuery = items.map(i => `ID eq '${i}'`).join(" or ");
    // replace in URL
    let url = `https://test.com/_api/web/lists/getbytitle('Document Separator Barcodes')/items?$orderBy=ID&$filter=${filterQuery}`