Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove null params in HttpParams

I have a criteria object for which some attributes can be null, if I don't do anything the query string include those like &p=undefined which is not desirable since at the WebApi these come as"null" instead of null So given this in the Angular client

      return this._http
          .get<ExposureDifference[]>(AppSettings.ExposureRunDataQueryString, {params : <any>criteria, withCredentials: true}) 
          .catch<any, ExposureDifference[]>(this._trace.handleError("GET " + AppSettings.ExposureRunDataQueryString + criteria, []))
          .finally(() => this.isLoading = false);

I could get the query string as

http://localhost:63037/api/exposureRuns/data/?id=3&secsymb=undefined&fund=EL&esectype=SWAP_CDS

Is there a way to exclude the undefined parameters from the query string?

like image 771
Anand Avatar asked Dec 08 '17 04:12

Anand


3 Answers

You should filter them client side using JavaScript's delete (MDN) keyword if they have a value of undefined (which is different than the key not being in the object at all):

if (queryObject.secsymb === undefined) {
  delete queryObject.secsymb;
}

and then use a default method parameter in your controller method:

GetExposureRunsData(int id, string fund, SecType sectype, string secsymb = null)

If you ensure that the query string parameter is not included then your parameter will default to null

like image 58
Sara M Avatar answered Sep 16 '22 15:09

Sara M


That's what I usually do. Works like a charm.

    getDocumentsReport(filter: object) {
        let params = new HttpParams();
        Object.keys(filter).forEach(
            key => filter[key] && (params = params.append(key, filter[key]))
        );
    
        return this.http.get<object>(
            environment.apiServer + '/api/reports/documents',
            {
                params
            }
        );
    }
like image 32
Eugene Kulabuhov Avatar answered Sep 18 '22 15:09

Eugene Kulabuhov


Try this function

removeNullValuesFromQueryParams(params: HttpParams) {
  const paramsKeysAux = params.keys();
  paramsKeysAux.forEach((key) => {
    const value = params.get(key);
    if (value === null || value === undefined || value === '') {
      params['map'].delete(key);
    }
  });

  return params;
}

And in your Intercept Service, set the Params of Request equals the return of the removeNullValuesFromQueryParams(req.params), function.

like image 39
Lucas Simões Avatar answered Sep 18 '22 15:09

Lucas Simões