我正在尝试实现Angular Interceptor for Exceptions。至少要一个。我有一个令牌,当它的旧enogh后端抛出TokenAlmostExpired exception时。此异常包含errorCode = 101。在拦截器中,我正在检查代码为101,然后需要将POST request发送到后端的/refresh endpoint,以便刷新令牌。

.factory('errorInjector',['$injector', function ($q, $injector) {

    var vm = this;

    var errorInjector = {
        'response': function (response) {
            console.log(response);
            return response;
        },
        'responseError': function (rejection) {
            if (JSON.stringify(rejection.data.errorCode) === JSON.stringify(101)) {
                vm.getRefreshToken();
            }
            return $q.reject(rejection);
        }
    };
    return errorInjector;
}]);




.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push('errorInjector');
    }]);


$ http

但是在拦截器级别存在一个问题,我不能仅仅依赖于$http,因为存在Circular dependency found: $http <- errorInjector <- $http <- $templateFactory <- $view <- $state

$范围

而且我不能将getRefreshToken()函数放入$scope,因为$ scope依赖项还提供了“循环依赖项”。

$喷油器

var http = $injector.get('$http');


效果不佳,给了我错误的答案。

那么,如何在拦截器中捕获异常,然后从那里进行$ http请求呢?

最佳答案

拦截器

(function (angular) {
    'use strict';

    angular.module('services').factory("httpInterceptor", [
        'errorLauncher',
        '$q',
        function (errorLauncher, $q) {
            return {
                'requestError': function (rejection) {
                    if (rejection.status === 101) {
                        errorLauncher.pushInErrorMessage(rejection);
                    }
                    return $q.reject(rejection);
                },
                'responseError': function (rejection) {
                    if (rejection.status === 101) {
                        errorLauncher.pushInErrorMessage(rejection);
                    }
                    return $q.reject(rejection);
                }
            };
        }]);
})(angular);


和错误处理程序服务

(function (angular) {
    'use strict';

    angular.module('services').factory("errorLauncher", [
        '$rootScope',
        function ($rootScope) {
            return {
                'pushInErrorMessage': function (rejection) {
                    $rootScope.$emit('theTokenWillDieSoon');
                }
            };
        }]);
})(angular);


现在是主应用程序控制器

(function (angular) {
    'use strict';

    angular.module('controllers').controller("globalCtrl", [
        '$rootScope',
        '$http',
        function ($rootScope, $http) {
            $rootScope.$on('theTokenWillDieSoon', function () {
                // http from here
            });
        }]);
})(angular);

10-08 07:18
查看更多