Sam Sam - 6 months ago 16
AngularJS Question

How can I use angularjs promise chain in a service and controller?

I found this plnkr link on the web but I need use it with 2 or 3 more ajax calls which doesn't require an argument from the first ajax call. How can I do it with error handling?

var app = angular.module("app", []);

app.service("githubService", function($http, $q) {

var deferred = $q.defer();

this.getAccount = function() {
return $http.get('https://api.github.com/users/haroldrv')
.then(function(response) {
// promise is fulfilled
deferred.resolve(response.data);
return deferred.promise;
}, function(response) {
// the following line rejects the promise
deferred.reject(response);
return deferred.promise;
});
};
});

app.controller("promiseController", function($scope, $q, githubService) {

githubService.getAccount()
.then(
function(result) {
// promise was fullfilled (regardless of outcome)
// checks for information will be peformed here
$scope.account = result;
},
function(error) {
// handle errors here
console.log(error.statusText);
}
);
});


http://plnkr.co/edit/kACAcbCUIGSLRHV0qojK?p=preview

Answer

You can use $q.all

var promises=[
$http.get(URL1),
$http.get(URL2),
$http.get(URL3),
$http.get(URL4)
];

$q.all(promises).then(function(response){
console.log('Response of Url1', response[0]);
console.log('Response of Url2', response[1]);
console.log('Response of Url3', response[2]);
console.log('Response of Url4', response[3]);
}, function(error){

});

I have forked your plunkr with $q