AngularJS $资源错误处理与回调 [英] AngularJS $resource Error Handing with Callback
问题描述
我有一个工厂,用于查询定制的API我建有多个服务。回调所有的工作,但我想知道我怎么能有任何的错误处理,同时获取。
I have a factory that has multiple services for querying a custom API I built. The callbacks all work, but I'm wondering how I can have any error handling while fetching.
.factory('customApiService', function ($resource) {
return {
yelp: function (businessId, callback) {
var api = $resource('../../api/Yelp/:businessId', {
businessId: businessId
}, {
fetch: 'JSONP',
'query': { isArray: false }
});
api.fetch(function (response) {
callback(response);
});
},
tripAdvisor: function (hotelId, callback) {
var api = $resource('../../api/TripAdvisor/:hotelId', {
hotelId: hotelId
}, {
fetch: 'JSONP',
'query': { isArray: false }
});
api.fetch(function (response) {
callback(response);
});
}
}
});
和控制器中使用此工厂的例子:
And an example of using this factory in a controller:
.controller('yelpCtrl', [
'$scope', 'customApiService', function ($scope, customApiService) {
customApiService.yelp("yelpIdHere", function (d) {
//On successful callback run code
});
customApiService.tripAdvisor("tripAdvisorIdHere", function (d) {
//On successful callback run code
});
}
])
目前,如果有任何不良反应(404,500,504等),回调将不会触发。
Currently if there is any bad response (404, 500, 504, etc), the callback is not fired.
推荐答案
不得不改变我厂返回一个errorCallback以及一个成功的回调:
Had to change my Factory to return an errorCallback as well as a successful callback:
.factory('customApiService', function ($resource) {
return {
yelp: function (businessId, callback, errorCallback) {
var api = $resource('../../api/Yelp/:businessId', {
businessId: businessId
}, {
fetch: 'JSONP',
'query': { isArray: false }
});
api.query(function (response) {
callback(response);
},
function (error) {
errorCallback(error);
});
},
tripAdvisor: function (hotelId, callback, errorCallback) {
var api = $resource('../../api/TripAdvisor/:hotelId', {
hotelId: hotelId
}, {
fetch: 'JSONP',
'query': { isArray: false }
});
api.query(function (response) {
callback(response);
},
function (error) {
errorCallback(error);
});
}
}
});
所以,现在在控制器中,我有第二个函数作为参数来我厂通话将处理任何错误:
So now in the controller, I have a second function as a parameter to my factory calls which will handle any errors:
.controller('yelpCtrl', [
'$scope', 'customApiService', function ($scope, customApiService) {
customApiService.yelp("yelpIdHere", function (d) {
//On successful callback run code
},
function(e){
//Do error handling here
});
customApiService.tripAdvisor("tripAdvisorIdHere", function (d) {
//On successful callback run code
},
function(e){
//Do error handling here
});
}
])
这个答案似乎帮助
这篇关于AngularJS $资源错误处理与回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!