Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send null as a value in ngResource AngularJS

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?

like image 313
Hengjie Avatar asked Mar 11 '14 02:03

Hengjie


1 Answers

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();
like image 142
jbielick Avatar answered Oct 09 '22 22:10

jbielick