Angular 6 HttpClient set param date only if its not null

Viewed 9493

I am trying to pass parameter to URL. For which I am using Angular HttpParams. How do I set date param only if date is not null or undefined?

Code:

let params = new HttpParams()
   .set('Id', Id)
   .set('name', name)

if (startDate !== null) {
    params.set('startDate', startDate.toDateString());
}

if (endDate !== null) {
    params.set('endDate', endDate.toDateString());
}
2 Answers

set does not mutate the object on which it is working - it returns a new object with the new value set. You can use something like this:

let params = new HttpParams()
   .set('Id', Id)
   .set('name', name)

if (startDate != null) {
    params = params.set('startDate', startDate.toDateString());
}

if (endDate != null) {
    params = params.set('endDate', endDate.toDateString());
}

Note how the params object is being reassigned. Also note the use of != to protect against both null and undefined.

Instead of using the HttpParams object you can define and mutate your own object and pass it within the http call.

let requestData = {
  Id: Id,
  name: name
}
if (startDate) {
//I am assuming you are using typescript and using dot notation will throw errors 
//unless you default the values
  requestData['startDate'] = startDate
}
if (endDate) {
  requestData['endDate'] = endDate
}

//Making the assumption this is a GET request
this.httpClientVariableDefinedInConstructor.get('someEndpointUrl', { params: requestData })
Related