kevin su kevin su - 20 days ago 9
AngularJS Question

angular: passing data to $resource service

Hi there I write a service of $resource for connecting the api.
here is the code in service.js

.factory('selfApi2', function ($resource, localStorageService) {
var AB = {
data: function (apiURL, header, data, params) {
return $resource("http://localhost:4000/api" + apiURL, null, {
update: {
method: 'POST',
headers: header,
data: data,
params: params
}
});
}
};
return AB;
})


in my controller.js

var header = {
'Content-Type': 'application/x-www-form-urlencoded'
};
var myData = {
'phone': '12345678'
};
selfApi2.data('/tableName',header,{where:{"name":"kevin"}).update(myData, function(result){
console.log("update Kevin's phone succeed",result);
})


it works. But why the variable myData should put inside the update() part rather than the data() part?

Answer

In your case, the data() is a function which will just create a ReST resource which would expose rest apis get save query remove delete as default.

So in this data() call you are just creating the rest resources. Passing myData with this function would not make any sense. The data() call would return the Resource instance which will have your update api function which accepts the parameters.

And, passing your data at api construction time does not make sense.

Here is the complete reference