すべての ngResource ベースのサービスのネットワーク関連のエラーを 1 か所で処理する方法を探しています。
この回答から、単一のリソース内のすべてのアクションに対してカスタム インターセプターを定義できることがわかりました。angularjs によって作成されたデフォルト アクションを変更し、そこにカスタム インターセプタを渡すことは可能ですか?
すべての ngResource ベースのサービスのネットワーク関連のエラーを 1 か所で処理する方法を探しています。
この回答から、単一のリソース内のすべてのアクションに対してカスタム インターセプターを定義できることがわかりました。angularjs によって作成されたデフォルト アクションを変更し、そこにカスタム インターセプタを渡すことは可能ですか?
これが私の解決策です:
angular.module('server-error', [])
.factory('ErrorResponseInterceptor', function($rootScope, $q) {
return {
responseError: function(rejection) {
var message = null;
switch (rejection.status) {
case 0:
message = "Unknown network error when loading " + rejection.config.url;
break;
default:
message = rejection.status + " " + rejection.statusText + " when loading " + rejection.config.url;
}
$rootScope.$broadcast('event:error-serverError', message);
return $q.reject(rejection);
}
};
})
//for $http
.config(function($httpProvider) {
$httpProvider.interceptors.push('ErrorResponseInterceptor')
})
//and for ngResource actions
.config(function($resourceProvider) {
var default_actions = $resourceProvider.defaults.actions;
angular.forEach(default_actions, function(action) {
action['interceptor'] = {
responseError: 'ErrorResponseInterceptor'
}
})
})
ここ(セクション「インターセプター」) に記載されているように、$http プロバイダーでインターセプターをセットアップできます。