I have a array named selectedItems that is populated from a multi-select dropdown button. SelectedItems could looks like this if all options were selected:
this.selectedItems: SearchItem[]= [
{"id":"abee232","itemName":"Attractions"},
{"id":"b6b1a23","itemName":"Artists"},
{"id":"08a58c8","itemName":"Performing Arts"},
{"id":"444d047","itemName":"Sports"}
];
I need to add the id values, however many have been selected, as parameters in a http GET request. Right now my logic looks like this.
private addRequestOptions(params: SearchItem[]): RequestOptions {
let options: RequestOptions = new RequestOptions();
options.params = new URLSearchParams();
if (params != null) params.forEach((p: SearchItem) => {
options.params.append("&collectionId", p.id);
})
console.log(options)
return options;
}
sortResults(){
let options: RequestOptions = this.addRequestOptions(this.selectedItems);
this.pendingCardsService.collectionUuidUrl = 'http://address/cards/topbrands?perPage=25', options;
this.pendingCardsBrandCollection();
}
With my SearchItem interface looking like this:
export interface SearchItem {
id?: string;
itemName?: string;
}
Right now this creates a requestOptions object that has the values in it as an array but my http requests do not show this in the query string parameters field within the network tab. It seems that the addRequestOptions() is working correctly but not being applied properly to the get request. The goal is to end up with a URL something like this:
'http://address/cards/topbrand?perpage=25&collectionId=idValue&collectionId=idValue&collectionId=idValue'
I am stuck how to accomplish this. Any help/tips/suggestions would be much appreciated.
UPDATE w/final code
My issue was with me having hard coded in 'http://address/cards/topbrands?perPage=25'
?perPage=25 was being read as params (rightfully so) and therefore the addition of the ids were not being appended since params were already present. My final code ended up looking like this that got it working properly:
fetchPendingCardsBrandCollection(ids: SearchItem[], pageSize = '25'):Observable<Card[]> {
const params = new URLSearchParams();
params.set('perPage', pageSize);
ids.forEach(id => params.append('collectionId', id.id));
return this.http.get(this.collectionUuidUrl, {params: params})
.map(this.extractData)
}
With my function calling this http request function passing SearchItems as a parameter. Big thanks for @Praveen M for the assistance and @Jota.Toledo for the solution!