我在服务中有以下代码,我从控制器调用fetchData函数。
服务
app.service("geturl", function($http) {
urllist = [];
geturl.fetchData = function() {
var data = [];
for (i = 0; i < urllist.length; i++) {
(function(index) {
return $http.get(geturl.urllist[index], {
timeout: 8000
})
.then(function(response) {
data[index] = response.data;
});
}(i);
return data;
});
};
});
我想在控制器中编写$ http.get的成功和错误功能,因为在UI中需要它,我该怎么办呢?
答案 0 :(得分:3)
..我想写一下$ http.get的成功和错误功能 控制器..
通常,.then()
函数有两个函数参数。第一个参数是成功处理程序,第二个参数是错误处理程序。
$http.get(url,options).then(function (response){
//success handler function
},function(error){
//error handler function
})
或者,您可以单独指定.success
和.error
功能。
$http.get(url,options).success(function (response){
//success handler function
}).error(function(error){
//error handler function
})
<强>更新强>
从您的代码中,您似乎打算从服务geturl
返回一些内容并在其中提供回调。这不是应该如何完成的。您应该从您的服务中退回承诺。
...
app.service("geturl",function($http){
...
getData:function(){
return $http.get(url,options);
}
...
});
...
并处理使用服务的模块中的成功/错误回调
geturl.getData().success(function(){
//handle success
}).error(function(){
//handle error
})
如果您需要发出多个http请求,永远不会使用for循环。请记住,一切都是异步的,并且您不能保证在创建新请求之前从先前的请求之一获得响应。在这种情况下,您应该使用$q service。有关详细信息,请参阅@ pankajparkar的答案
答案 1 :(得分:2)
好像你想在所有ajax完成后返回一个数据,你可以使用$q.all()
<强>服务强>
app.service("geturl", function($http, $q) {
this.urllist = [];
this.fetchData = function() {
var data = [], promises = [];
for (i = 0; i < urllist.length; i++) {
(function(index) {
var promise = $http.get(geturl.urllist[index], {
timeout: 8000
})
.then(function(response) {
data[index] = response.data;
});
promises.push(promise); //creating promise array
}(i);
};
return $q.all(promises).then(function(resp){
return data; //returning data after all promises completed
});
};
});