Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 HttpClient set param date only if its not null

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());
}
like image 959
dps Avatar asked Sep 19 '18 14:09

dps


1 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.

like image 53
Kirk Larkin Avatar answered Oct 10 '22 11:10

Kirk Larkin