我在服务中有以下代码,并且我正在从 Controller 调用 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;
});
};
});
我想在 Controller 中编写 $http.get 的成功和错误函数,因为 UI 中需要它,我该怎么做?
最佳答案
..I want to write the success and error function of $http.get in the controller..
通常,.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
返回一些内容并在那里提供回调本身。这不是应该做的事情。您应该从您的服务中返回一个 promise 。
...
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 的回答
关于javascript - 服务 Controller 中的成功和错误函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30977806/