简体   繁体   中英

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

I am doing a custom Oauth2 authentication module. I have a requestExecutor factory:

     $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();
           }
        });

and Http Interceptor:

'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);
       }

So when I execute a request and get 403 response error from the server I want to send the full request to the listener of CONST.FORBIDDEN (the only thing that is missing is the callbacks from the $http().then() promise). The reason is that I want to execute the failed request again after I finish with the refreshing the access token.

My questions are:

  1. Where are stored $http().then() promises?
  2. Can to get $http().then() promises?
  3. How can I implement 2.?

No sure about your intention, there would probably be better solutions, but you can register the callback handlers in the config object and access them in the interceptor. plnkr

But here is a better design. angular-app/securityInterceptor You will do the refreshing in the interceptor and execute the request again. If the second request was successful you return the result, which will be processed by your 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;
        }
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM