Angularjs $http 承诺;从 $http().then(fn1, fn2) 获取回调函数 fn1 和 fn2

Angularjs $http promise; Get the callback functions fn1 and fn2 from $http().then(fn1, fn2)

我正在做一个自定义的 Oauth2 身份验证模块。我有一个 requestExecutor 工厂:

     $http({
        url: requestObject.url, 
        method: requestObject.method, 
        cache: requestObject.cache, 
        headers: requestObject.headers, 
        data: requestObject.data})

        .then(function (resData) {
           if (requestObject.callback) {
               requestObject.callback(resData.data);
           }
         }, function () {
           if (requestObject && requestObject.customErrorCallback) {
               requestObject.customErrorCallback();
           }
        });

和 Http 拦截器:

'responseError': function (rejection) {
       console.log(rejection)
       switch (rejection.status) {
               case 401 :
               {
                  $rootScope.$emit(CONST.UNAUTHORIZED);
                  break;
               }
               case 403 :
               {
                  $rootScope.$emit(CONST.FORBIDDEN, rejection.config);
                  break;
               }
            }
            return $q.reject(rejection);
       }

所以当我执行请求并得到 403 响应错误 我想从服务器向 CONST.FORBIDDEN 的侦听器发送完整请求(唯一缺少的是来自 $http().then() promise 的回调)。原因是我想在完成刷新访问令牌后再次执行失败的请求。

我的问题是:

  1. $http().then() 承诺存储在哪里?
  2. 可以得到$http().then()承诺吗?
  3. 如何实施 2.?

不确定您的意图,可能会有更好的解决方案,但您可以在配置对象中注册回调处理程序并在拦截器中访问它们。 plnkr

但这里有一个更好的设计。 angular-app/securityInterceptor 您将在拦截器中进行刷新并再次执行请求。如果第二个请求成功,您 return 结果将由您的 success/error-handlers.

处理
$scope.fetchAsync = function(forceError) {
    function successHandler(result) {
        $scope.content = result.data;
    }

    function errorHandler(result) {
        $scope.content = result;
    }   

    $scope.content = 'Loading...';

    $http.get(forceError ? 'not-found' : 'test.txt', {
      handler: {
        success: successHandler,
        error: errorHandler
      }
    }).then(successHandler, errorHandler);
}

$httpProvider.interceptors.push(function($q) {
    return {
        'responseError': function(rejection) {
            console.log(rejection.config.handler);
            return rejection;
        }
    };
});