Value returned from Angular Resource JS $ POST Server output mapping not

I have a factory resource with a POST method called update:

PnrApp.factory('Feed', function ($resource, $cacheFactory, $q, $rootScope) { var Feed = $resource('api/feeds/:post', { post: 'post' }, { get: { method:'GET' }, update: { method: 'POST' } }); return Feed; 

});

When I call the method, it sends data to the server as expected:

  $rootScope.toggleStar = function (post, feedname) { var updated = Feed.update(post); this.child.StarId = updated.StarId; } 

And the server will return the correct values ​​(note the StarId in this json):

 {"Name":"13 Ways to Act Like A Business Owner","ItemDate":"June 6, 2013","Url":"/post/13-Ways-to-Act-Like-A-Business-Owner-Stop-Acting-Like-an-Advisor-All-the-Time-(6-min-03-sec).aspx","StarImg":"bulletstar-on.png","StarId":1324,"StarDate":"0001-01-01T00:00:00","FeedCount":0,"FeedId":19,"SourceIcon":null,"IsBroken":false,"ItemId":"01"} 

However, if you look at the updated var value for StarId, notice how it is "0":

enter image description hereenter image description here

Can someone explain why this is so, and how can I get the return values ​​in this situation?

+4
source share
1 answer

Your var updated = Feed.update(post); makes an asynchronous call to the server and returns immediately, and the updated object is updated as soon as the server returns data. Therefore, I think you are trying to access the updated. The start is too early. From angular doc :

It is important to understand that calling the method of the $ resource object immediately returns an empty reference (object or array depending on isArray). As soon as the data is returned from the server, the existing link is filled with actual data. This is a useful trick, because usually a resource is assigned to a model, which is then displayed in a view. The presence of an empty object does not lead to rendering, as soon as the data arrives from the server, then the object is filled with data, and the view automatically re-displays itself, showing new data. This means that in most cases, you never need to write a callback function for action methods.

Try something like this:

 $rootScope.toggleStar = function (post, feedname) { var updated = Feed.update(post, function(f) { this.child.StarId = f.StarId; }); } 
+3
source

Source: https://habr.com/ru/post/1485598/


All Articles