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?
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
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
}
);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With