Reputation: 1304
I'm using two factory calls in my controller. In both catches, I want to call separate functions to handle the errors.
what I have :
someFactory.functionOne().then(function (data) {
$scope.one = data;
}).catch(functionToHandleOne());
someFactory.functionTwo().then(function (data) {
$scope.two = data;
}).catch(functionToHandleTwo());
Is the any better way I can do this with $q.all() like
$q.all({
one: someFactory.functionOne(),
two: someFactory.functionTwo()
}).then (function (data) {
$scope.one = data.one;
$scope.two = data.two;
}).catch(
//here I have to call functions functionToHandleOne() and functionToHandleTwo() according to error caused which function call
);
Upvotes: 1
Views: 2132
Reputation: 2569
Your solution is perfectly fine. You are missing the error callback function in your 'catch' and the error argument of course.
An example:
$q.all({
one: someFactory.functionOne(),
two: someFactory.functionTwo()
}).then (function (data) {
$scope.one = data.one;
$scope.two = data.two;
}).catch(function(e){
if(e.argument == 'error1')
functionToHandleOne()();
else
functionToHandleTwo()();
});
Upvotes: 1
Reputation: 876
var app = angular.module('plunker', []);
app.factory('json',function($q,$http){
return function(files){
var promises = files.map( function(file){
var deffered = $q.defer();
$http({
url : file,
method: 'GET'
}).
success(function(data){
deffered.resolve(data);
}).
error(function(error){
deffered.reject();
});
return deffered.promise;
})
return $q.all(promises);
}
});
app.controller('MainCtrl', function($scope,json) {
$scope.name = 'World';
json(['a.json','b.json']).then(function(datas){
$scope.a = datas[0]
$scope.b = datas[1]
})
});
there in above full code you could find everything you needed. like
$q passed in factory and if you have multiple function there you can call all into single factory and make them really custom s your need.
you can see in controller as show in below code it will return datas.
json(['a.json','b.json']).then(function(datas){
$scope.a = datas[0]
$scope.b = datas[1]
})
"datas" returns multiple values of all calls so you need to use with array.
Please let me know if solve or need more research
Upvotes: 1