Remove null params in HttpParams
V

4

10

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?

Verb answered 8/12, 2017 at 4:53 Comment(1)
You may also want to keep an eye on this thread: github.com/angular/angular/issues/20564 Many users complained about this behavior of Angular2 given the fact that it didn't to behave like this (null/undefined values where being completely omitted from the query string).Prosecutor
R
5

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

Reams answered 8/12, 2017 at 5:0 Comment(1)
Hi @Alex M The undefined attribute was not deleted, typescript set it to null instead of undefined and the WebApi got it as "null" so the problem was not solvedVerb
D
3

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
            }
        );
    }
Dotdotage answered 8/9, 2020 at 6:18 Comment(0)
C
1

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.

Chappy answered 11/7, 2020 at 0:4 Comment(0)
S
0

You can try this:

this.httpClient.get('../api/path', { 
  params: Object.entries(queryParameterObject).reduce((queryParams, [key, value]) => queryParams.set(key, value), new HttpParams());
});

It worked for me.

Sclerous answered 18/12, 2017 at 8:1 Comment(2)
I am getting params as "null" with the above code - so this solution does not work for me.Verb
It looks like you are converting your parameters into a string before calling this. If you need to convert them into string, you can do that in queryParams.set(key, value) instead and pass the correct value of the parameters as input.Sclerous

© 2022 - 2024 — McMap. All rights reserved.