我正在尝试通过自定义服务中的$http
服务进行ajax调用。然后我想在我的控制器中自定义自定义服务中收到的数据。
我将自定义数据函数包装在控制器内的$interval
内:通过这种方式,我可以在收到数据时自定义数据。
问题是:在服务中正确记录数据时,服务似乎没有返回任何内容,尽管它应该已经返回({{ 1}})
所以return response.data.Items
无限循环,我无法自定义数据。
$interval
您可以说:只需在自定义服务中移动自定义数据功能即可。首先,我不想这样做。其次它甚至没有意义:$ scope在服务中不可用,所以在任何情况下我都应该等待$ http回复。
答案 0 :(得分:1)
有几件事我想指出那里。
从$http
方法返回this.getjson
承诺,以便您可以在从中获取数据时链接该承诺。
this.getjson = function() {
//returned promise here
return $http.get("http://localhost:3000/one")
.then(function(response) {
console.log(response.data.Items); //data logged correctly
return response.data.Items;
});
}
var new_items = ajaxcall.getjson()
行未存储getjson
调用返回的数据,它将具有您当前获取的未定义值。完成上述更改后,new_items
将按ajaxcall.getjson
保留承诺。之后使用$q.when
来关注获得解决的承诺&检查其.then
函数内的数据。
customize_data = $interval(function() { //loops indefintely, new_items=undefined, why?
$q.when(new_items).then(function(res) {
if (customizeData) {
//Do Logic
}
})
}, 200);
旁注:您可能会遇到此代码的问题,因为每个时间间隔都有
200ms
时间。在完成最后一次调用之前可以进行多次ajax调用(这将是一种意外行为)。至 解决此问题,您可以使用$interval.cancel(customize_data); //once desired interval work has done
答案 1 :(得分:0)
如果你想获得返回数据,你会写一个工厂而不是服务!
代码:
myApp.factory('ajaxcall', ['$http', function($http) {
return {
getjson : function () {
$http.get("http://localhost:3000/one")
.then(function(response) {
console.log(response.data.Items); //data logged correctly
return response.data.Items;
});
}
}
}])
答案 2 :(得分:0)
您滥用异步调用返回的promise
。以下是您需要在控制器中更改数据的内容:
ajaxcall.getjson()
.then(function(new_items) {
// customize data
// this part should go here as well
for(var i=0; i<new_items.length; i++) {
$scope.items.push(new_items[i]);
}
});
无需使用intervals
或timeouts
。请注意,ajaxcall.getjson()
不返回您的数据,它会返回与您的商品一起解决的承诺。
了解角度为promises的内容。
答案 3 :(得分:0)
从服务
进行http调用时使用promisemyApp.service('ajaxcall', ['$http', '$q', function($http, $q) {
this.getjson = function() {
var q = $q.defer();
$http.get("http://localhost:3000/one")
.success(function(data) {
console.log(data); //data logged correctly
q.resolve(data);
})
.error(function(err) {
q.reject(err);
});
return q.promise;
}
}]);
控制器中的变化等待承诺
ajaxcall.getjson()
.then(function(data){
console.log(data);
});