Search code examples
angulartypescriptfetchhttpclientweb-frontend

Passing parameters using fetch api


I am trying to pass parameters using fetch after converting the code from angular httpclient (it was part of the task). Herein is the part of the code before I made changes to it.

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);

I converted the entire code the usage of fetch API. Herein what it looks like now:

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);
             })
        );
    }

However, I am unable to pass in the parameters 'params' in this case. Can you guys please help me out on how to go about it and how should it be structure the code when it comes to the part of the fetch function?


Solution

  • To add URL params to a request using fetch, you need to append them to the fetch url (and also set the correct header names):

    const params = new URLSearchParams({ name });
    
    if (this.customLookupAddress) {
      params.set('lookup', this.customLookupAddress);
    }
    if (this.customGatewayAddress) {
      params.set('gateway', this.customGatewayAddress);
    }
    fetch(`${targetUrl}?${params}`, { headers: { 'Accept': 'application/json' } })
      .then(res => res.json())
      // ...