我在 Controller 中使用了两个工厂调用。在这两个捕获中,我想调用单独的函数来处理错误。
我有什么:
someFactory.functionOne().then(function (data) {
$scope.one = data;
}).catch(functionToHandleOne());
someFactory.functionTwo().then(function (data) {
$scope.two = data;
}).catch(functionToHandleTwo());
有什么更好的方法可以用 $q.all() 来做到这一点
$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
);
最佳答案
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]
})
});
在上面的完整代码中,您可以找到您需要的一切。喜欢
$q 在工厂中传递,如果您有多个函数,您可以将所有函数调用到单个工厂中,并使它们真正满足您的需要。
您可以在 Controller 中看到,如下面的代码所示,它将返回数据。
json(['a.json','b.json']).then(function(datas){
$scope.a = datas[0]
$scope.b = datas[1]
})
“datas”返回所有调用的多个值,因此您需要与数组一起使用。
如果解决或需要更多研究,请告诉我
卡贾明
关于javascript - $q.all() 中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37717559/