PnrApp.factory('Feed',function ($resource,$cacheFactory,$q,$rootScope) { var Feed = $resource('api/Feeds/:post',{ post: 'post' },{ get: { method:'GET' },update: { method: 'POST' } }); return Feed;
});
$rootScope.toggleStar = function (post,Feedname) { var updated = Feed.update(post); this.child.StarId = updated.StarId; }
服务器返回正确的值(注意这个json中的StarId):
{"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"}
但是,如果你查看var更新的StarId返回值,请注意它是如何“0”:
有人可以解释为什么会这样,以及如何在这种情况下获得返回值?
解决方法
It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering,once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means ththeat in most case one never has to write a callback function for the action methods.
尝试这样的事情:
$rootScope.toggleStar = function (post,Feedname) { var updated = Feed.update(post,function(f) { this.child.StarId = f.StarId; }); }