Home > OS >  Passing parameters using fetch api
Passing parameters using fetch api

Time:06-03

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?

CodePudding user response:

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())
  // ...

CodePudding user response:

It looks like you are not setting params in the object of your fetch function.

I think it should be something like this

  const data$ = new Observable(observer => {
        fetch(targetUrl, { params: params, headers: { 'responseType': 'json'}, method: 'GET'})
          .then(response => response.json()) 
          .then(namedSelection => {
            observer.next(namedSelection);
            observer.complete();
          })
          .catch(err => observer.error(err));
      });

You can check out the other options here: https://angular.io/guide/http#requesting-data-from-a-server

  • Related