I'm using AngularJS 1.2.1's ngResource and I'm trying to send null
as a value in the parameters in a PUT request. Unfortunately, when it is set, Angular will ignore it the parameter and not send it.
Here's some example code:
var User = $resource('/comments/:id', {id:'@id'}, {
destroy: { method: 'PUT', params: {content: null} }
});
var user = User.destroy({id:123}, function() {});
Angular will instead ignore content
and not send the key nor the null value.
How can I make Angular send null?
As Lèse has pointed out, the javascript type null
is not a valid value for a URL parameter.
A javascript null
value isn't the same as the string 'null'
. So if you wanted your URL to look like /comments/123?content=null
just provide a string 'null'
. URL parameters are not JSON and a null
value in javascript doesn't mean the same thing as content=null
because in the latter case, null would be interpreted by any given server as a string value.
Angular's $http service filters out null and undefined values in the params object before constructing a url with them because there's no standardized way to send undefined
as a "value" to a server. It just doesn't make sense. However, if you wanted to send a string like 'undefined'
or 'null'
that's fine, but it require implementation on the server side to interpret it as such.
If you're making a PUT
request, why is some of your data being JSON serialized within the resource and some of it being sent via a URL parameter? Maybe the example code is just poorly represented, but in that example you're sending a PUT
request with the response body of {"id": 123}
and the url /comments/123
. Isn't that redundant? Why aren't you sending the content
property and data in the JSON string to the server? Then it would actually have the null
value you're looking for because JSON strings can represent a null
type value. Also, if you're deleting/destroying a record, why aren't you using a DELETE
request, but instead aliasing a destroy method with a PUT request?
So why not something like this? I'm not sure what the User
has to do with it...
var Comment = $resource('/comments/:id', {id: @id}, {
destroy: {method: 'PUT'}
});
new Comment({id: 123, content: null}).$destroy();
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