success and error function in the controller for a service

user2851669 picture user2851669 · Jun 22, 2015 · Viewed 16.3k times · Source

I have the following code in a service and I am calling fetchData function from the controller.

Service

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;
        });
    };
});

I want to write the success and error function of $http.get in the controller since it is needed in the UI, how can I go about it?

Answer

nalinc picture nalinc · Jun 22, 2015

..I want to write the success and error function of $http.get in the controller..

Usually, the .then() function takes two function arguments. The first argument is the success handler and the second as an error handler.

$http.get(url,options).then(function (response){
    //success handler function
    },function(error){
  //error handler function     
  })

Alternatively, you can specify the .success and .error functions separately.

$http.get(url,options).success(function (response){
    //success handler function
    }).error(function(error){
  //error handler function     
  })

UPDATE: From your code, it seems that you intend to return something from your service geturl and providing the callbacks there itself. This is not how it is supposed to be done. You should return a promise from your service .

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

and handle the success/error callbacks in the module where you are consuming the service

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

In case you need to make multiple http requests, never ever use the for loop . Remember, everything is asynchronous and you are not guaranteed to get the response from one of the previous request before you make a new one. In such scenarios, you should use $q service. See @pankajparkar's answer for more details