加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:12:49 所属栏目:安全 来源:网络整理
导读:我有一个名为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; });
我有一个名为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;
  });      
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读