Home > Enterprise >  Why does my Angular http.delete send "null" instead of null?
Why does my Angular http.delete send "null" instead of null?

Time:05-14

I have the following in my Angular service:

this.$http.delete<void>(ApiDomain.superPlan, `/v1/Attendance?resultEventId=${resultEventId}&dueEventId=${dueEventId}`)

And this is the signature of the C# method being called:

        [HttpDelete(),
        public async Task<IActionResult> Delete(string resultEventId, string dueEventId)

The dueEventId passed in is sometimes null. Yet in the C# method, its value is "null" instead of null. How do I pass the actual null value?

CodePudding user response:

When JavaScript is concatenating strings, if it comes across null it will insert "null" into the given string.

console.log(`/v1/Attendance?resultEventId=${1}&dueEventId=${null}`);
// output: /v1/Attendance?resultEventId=1&dueEventId=null

To avoid that, you can avoid including the dueEventId query parameter at all if its value is null. Or leave the value empty: ASP.NET Core will interpret an empty string as null, as pointed out by Heretic Monkey in the comments.

CodePudding user response:

Rewrite to ommit param with null value

let params=new HttpParams().append("resultEventId","" resultEventId})
if(dueEventId){
   params=params.append("dueEventId","" dueEventId);
}
this.$http.delete<void>(ApiDomain.superPlan, `/v1/Attendance`,{params});

otherwise you are sending dueEventId="null" which is exactly what you observe.

  • Related