angularjs – 从Angular JS $资源POST返回的值不匹配服务器输出

前端之家收集整理的这篇文章主要介绍了angularjs – 从Angular JS $资源POST返回的值不匹配服务器输出前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个名为update的POST方法的资源工厂:

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

        });
return Feed;

});

当我调用方法时,它按预期将数据POST到服务器:

$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”:

有人可以解释为什么会这样,以及如何在这种情况下获得返回值?

解决方法

你的var更新= Feed.update(post);对服务器进行异步调用并立即返回,并在服务器返回数据后立即更新更新的对象.所以我想你尝试过早访问updated.StarId.从 angular doc

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;
  });      
}

猜你在找的Angularjs相关文章