[英]Error handling in $q.all()
我在控制器中使用了兩個工廠調用。 在這兩個陷阱中,我想調用單獨的函數來處理錯誤。
我有的 :
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
);
您的解決方案非常好。 當然,您在“捕獲”中缺少錯誤回調函數,並且缺少error參數。
一個例子:
$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()();
});
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是在工廠中傳遞的,如果您有多個功能,則可以將它們全部調用到一個工廠中,並使它們真正滿足您的需求。
您可以在控制器中看到,如下面的代碼所示,它將返回數據。
json(['a.json','b.json']).then(function(datas){
$scope.a = datas[0]
$scope.b = datas[1]
})
“數據”返回所有調用的多個值,因此您需要與數組一起使用。
請讓我知道是否需要解決或需要更多研究
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.