0
我有一个工作$ http.POST请求在一个工厂,其工作是获取一个列表对象并将其返回。这样简单,除了对象属性,我将它返回到刚刚生长的腿和树叶。我将解释:AngularJS推迟的承诺
只是有点问题了,现在,一切似乎是工作的罚款虽然
$scope.updateObj = function(num) {
console.log("Obj before:\n" + JSON.stringify($scope.Obj));
$scope.Obj.name = "Obj_" + num;
$scope.Obj.list = myFactory.getList($scope.Obj.name);
window.setTimeout(console.log("Obj after:\n" + JSON.stringify($scope.Obj)), 3000);
};
的执行console.log更新显示对象,就像在myController.js定义之前,和更新后的console.log具有正确的更新信息,但完全缺少list属性。
我在超时更新后设置了console.log检查Obj,看看请求是否只需要多一点时间,但我不认为它按预期工作。我认为这是一个异步的问题,但我还是比较新的,对于如何使用$ q服务我没有很好的把握。
tld; dr:我如何将$ http的response.data异步附加到对象属性?
myFactory.js
app.factory('myFactory', function($http) {
var service = {};
service.getList = function(name) {
try {
console.log("getting" + name);
var temp = $http({
method: 'POST',
url: 'yourmom.com',
headers: {
'Content-Type': 'application/json'
},
data: {list: name},
cache: true
}).then(
function success(response) {
alert(JSON.stringify(response.data.list)); // <- checks out & is exactly what I expect.
return response.data.list;
},
function error(response) {
throw error(response.status);
}
);
}
catch(err) {
alert(err);
return undefined;
}
};
return service;
});
myController.js
app.controller('GUIcontroller', ['$scope', 'myFactory', 'networkFactory', function($scope, myFactory, networkFactory) {
$scope.number = undefined;
$scope.networkInit = networkFactory.init();
$scope.Obj = {
id: 0,
name: "",
list: {}
};
$scope.updateObj = function(num) {
console.log("Obj before:\n" + JSON.stringify($scope.Obj));
$scope.Obj.name = "Obj_" + num;
$scope.Obj.list = myFactory.getList($scope.Obj.name);
console.log("Obj after:\n" + JSON.stringify($scope.Obj));
};
}]);
您必须回调传递给'setTimeout',而不是调用'的console.log()'立即通过它的结果 – Bergi
你的'getList'函数应该返回promise(并且你可以省略try-catch),并且你应该等待promise的结果而不是使用任意超时 – Bergi