gpt4 book ai didi

angularjs - 从 Angular JS $resource POST 返回的值与服务器输出不匹配

转载 作者:行者123 更新时间:2023-12-01 02:25:13 26 4
gpt4 key购买 nike

我有一个资源工厂,有一个名为 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;

});

当我调用该方法时,它会按预期将数据发布到服务器:
    $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"}

但是,如果您查看 StarId 的 var updated 返回值,请注意它是“0”:

enter image description here
enter image description here

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

最佳答案

您的 var updated = Feed.update(post);对服务器进行异步调用并立即返回 updated一旦服务器返回数据,对象就会更新。所以我猜你太早尝试访问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 - 从 Angular JS $resource POST 返回的值与服务器输出不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17043013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com