Good day, studying the work with resources in angular, came across the following code:

var News, //Ресурс newsInstance; //Экземпляр новости function updateNewsItem(){ newsInstance.published = false; newsInstance.$save(); } News = $resource('/api/news/:id/'); newsInstance = News.get({id: 3}, updateNewsItem); //Новость с id = 3, просто для примера 

I don’t understand how to call $ save () without prior declaration.

  • You still need to clarify how Javascript works. Well, essentially the question: after the line newsInstance = News.get ({id: 3}, updateNewsItem); newsInstance becomes an object that has a $ save function - zhenyab

2 answers 2

In the ngResource you can see the description of the returned object:

Set of resource options for the default set of resource options. The default set contains these actions:

 { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }; 

When the data is returned from the server, the resulting object will be an object of the Resource class and the above methods will be available to it with the $ prefix.

    The $save method is contained by default in the resource constructor and is available to be called from the resource instance.

    • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky