1

すべての ngResource ベースのサービスのネットワーク関連のエラーを 1 か所で処理する方法を探しています。

この回答から、単一のリソース内のすべてのアクションに対してカスタム インターセプターを定義できることがわかりました。angularjs によって作成されたデフォルト アクションを変更し、そこにカスタム インターセプタを渡すことは可能ですか?

4

2 に答える 2

1

これが私の解決策です:

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'
        }
    })
})
于 2015-10-01T10:25:16.473 に答える
0

ここ(セクション「インターセプター」) に記載されているように、$http プロバイダーでインターセプターをセットアップできます。

于 2015-09-30T08:36:30.567 に答える