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?
Usually, the
.then()
function takes two function arguments. The first argument is the success handler and the second as an error handler.Alternatively, you can specify the
.success
and.error
functions separately.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 .and handle the success/error callbacks in the module where you are consuming the service
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