AngularJs : event listener on http requests

2019-06-27 14:15发布

问题:

Since i'm using Oauth2 to protect my Api, i need to get a new access token before any http requets if the previous access token has expired.

I didn't used event listener much until now.

Here what i did for now (Please let me know if it is correct) :

ApplicationController.js :

app.controller('ApplicationController', function($rootScope, $scope, $localStorage, AuthService){

    // Listening event apiRequested
    $scope.$on('event:apiRequested', function(e) {

        AuthService.token();
        // Restore the access_token in case it has changed
        access_token = $localStorage.getObject('access_token');

    });

})

UserController.js :

$rootScope.$broadcast('event:apiRequested');

// Get Users around
return $http.post(domain+'/api/users?access_token='+access_token.key, data).then(function(response){
    return response;
});

First thing i'm not sure about ... Does $http is processed if the event already executed entirely?

So since i'm not sure, i'm thinking about adding a callback.

Here the idea :

$rootScope.$broadcast('event:apiRequested', function(response){

    if(response){

        // Get Users around
        return $http.post(domain+'/api/users?access_token='+access_token.key, data).then(function(response){
            return response;
        });

    }

});

Please let me know if it is possible to do that or should i use something else than event listener for that case.

回答1:

Why don't you use interceptors that is done to intercept HTTP request ? In your case, you shall add this very specific behaviour into the "request" part.

See an interceptor exemple bellow:

var $myService; // Add a constant that store the service
    $httpProvider.interceptors.push(['$location', '$injector', '$q', function($location, $injector, $q) {
                             return {

                               'request' : function(config){
                                 console.log("intercept request", config.url,config)
                                 // Your token shall be retreive in this part
                                 return config
                               },
                               'response' : function(config){
                                 $myService= $myService|| $injector.get('$myService'); // inject the service manually if constant is undefined
                                 console.log("intercept response", config)
                                 // Your token shall be retreive in this part
                                 return config
                               },
                                 'responseError': function(rejection) {

                                     console.log("responseError intercepted" , rejection);
                                      if (rejection.status === 403) {

                                         return $q.reject(rejection);

                                     } else if (rejection.status === 423) {



                                         return $q.reject(rejection);
                                     }else
                                          return $q.reject(rejection);
                                 }
                             };
                         }]);

Interceptors shall be defined into .config(["$httpProvider", function($httpProvider)