服务控制器中的成功和错误功能

success and error function in the controller for a service

我在服务中有以下代码,我正在从控制器调用 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的success和error函数,因为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     
  })

更新: 从您的代码来看,您似乎打算 return 从您的服务 geturl 中获得一些东西并在那里提供回调本身。这不是应该做的。您应该 return 服务承诺。

   ... 
   app.service("geturl",function($http){
     ...
     getData:function(){
        return $http.get(url,options);
     }
     ...               
   });
   ...

并在您使用服务的模块中处理 success/error 回调

geturl.getData().success(function(){
//handle success
}).error(function(){
//handle error
})

如果您需要发出多个 http 请求,永远不要使用 for 循环。请记住,一切都是异步的,您不能保证在发出新请求之前从先前的请求之一获得响应。在这种情况下,您应该使用 $q service。有关详细信息,请参阅@pankajparkar 的回答

似乎您想在所有 ajax 完成后 return 数据,您可以使用 $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
        });
    };
});