9

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());
}
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
dps
  • 135
  • 1
  • 3
  • 10

2 Answers2

18

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.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
  • 2
    You should avoid avoid != null except for "boolean", generally you juste write if(startDate) { if(endDate) { – xrobert35 Sep 19 '18 at 15:18
  • @xrobert35 Yes I knew this was a sensitive area - [This](https://basarat.gitbooks.io/typescript/docs/javascript/null-undefined.html) says what I went with is good to use (so does [this](https://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or-null)). – Kirk Larkin Sep 19 '18 at 15:20
  • 1
    @xrobert35 I have the param "page", so, `page=0` is a valid param for me, and `if (page)` will false, but wouldn't be... – serge Sep 19 '18 at 16:07
  • please vote for the conditional HttpParams set update feature: https://github.com/angular/angular/issues/26021 – serge Sep 19 '18 at 16:35
-2

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 })
Ronald91
  • 1,736
  • 1
  • 15
  • 23
  • imagine instead of startDate is the `page` param... `page` set to `0` will fail your `set`... – serge Sep 19 '18 at 16:10
  • 1
    more than that, requetData[page] == requestData[0]... not good ( probably `requestData['page']` instead? – serge Sep 19 '18 at 16:15
  • Thanks for the correction with the missing quotes and in your case you can do if(page!==undefined && page!==null). At that point you can still assign the page property to the object. – Ronald91 Sep 19 '18 at 17:06