After completing a task that involved converting code from Angular HttpClient to using fetch API, I encountered an issue with passing parameters. Below is the original code snippet before my modifications:
let activeUrl = new URL(this.serverAddress);
let targetUrl = activeUrl.origin + environment.apiBasePath + '/named_selection/' + componentId;
let params = new HttpParams().set('name', name);
if (this.customLookupAddress != "") {
params.set('lookup', this.customLookupAddress);
}
if (this.customGatewayAddress != "") {
params.set('gateway', this.customGatewayAddress);
}
return this.httpClient.get(targetUrl, { headers: { 'responseType': 'json' }, params: params }).pipe(
map((namedSelection) => {
this.namedSelections.set(componentId.toString() + '.' + name, namedSelection);
Below is the revised code where I converted the entire logic to use the fetch API:
let activeUrl = new URL(this.serverAddress);
let targetUrl = activeUrl.origin + environment.apiBasePath + '/named_selection/' + componentId;
let params = new HttpParams().set('name', name);
if (this.customLookupAddress != "") {
params.set('lookup', this.customLookupAddress);
}
if (this.customGatewayAddress != "") {
params.set('gateway', this.customGatewayAddress);
}
const data$ = new Observable(observer => {
fetch(targetUrl, { headers: { 'responseType': 'json'}, method: 'GET'})
.then(response => response.json())
.then(namedSelection => {
observer.next(namedSelection);
observer.complete();
})
.catch(err => observer.error(err));
});
return data$.pipe(
tap((namedSelection) => {
this.namedSelections.set(componentId.toString() + '.' + name, namedSelection);
})
);
}
I am currently facing a challenge in passing the 'params' in the fetch request. Can you provide guidance on how to address this and suggest any necessary changes to the structure of the code within the fetch function?