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());
}
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
.
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