Run code before starting services - AngularJS

1

Is there a way to run a code that runs before services?

Because I want to use the $http.defaults.headers function before starting the services so that I can instantiate the header on all services that I request, but it seems like it loads all the code and then returns that to me. The function that does this is below:

function get(url) {
        var deferred = $q.defer();
        $http.post(url,{'device_id':testedevice})
        .success(function (data) {
            deferred.resolve(data);
        })
        .error(function (error) {
            deferred.reject(error);
        });

        return deferred.promise;
    }

    get(base_url+"/api/access/token")
        .then(function (data) {
            if(!localStorage.getItem("access_token")){
                localStorage.setItem("access_token",data.token);
                $rootScope.keyUser = data.token;                                    
            }else{
                var userToken = localStorage.getItem("access_token");
                $rootScope.keyUser = userToken;
            }
    })
    .finally(function(){
        $rootScope.on(function(){
            $http.defaults.headers.get = {'access_token': userToken,'device_id':testedevice}  
        });
    });

PS: The header is applied, but after the services have already been called.

    
asked by anonymous 20.07.2016 / 21:37

2 answers

1

What you need is to create an interceptor using $httpProvider .

Maybe this link will help you Interceptor

    
22.07.2016 / 16:48
1

You can implement an interceptor exclusively for the $http service, and manipulate the headers directly.

module.factory('sessionInjector', ['SessionService', function(SessionService) {  
    var sessionInjector = {
        request: function(config) {

            // Trecho executado antes de todo request:

            if (!SessionService.isAnonymous) {

                config.headers['access_token'] = SessionService.userToken;
               config.headers['device_id'] = SessionService.testedevice; 
            }
            return config;
        }
    };
    return sessionInjector;
}]);

module.config(['$httpProvider', function($httpProvider) {  
    // .config() ocorre antes de .run(), guarantindo assim que
    // sessionInjector esteja definido e preparado antes da
    // inicialização da aplicação.

    // Adiciona o injetor de sessão à lista de interceptors do
    // serviço $http
    $httpProvider.interceptors.push('sessionInjector');
}]);

Original source: link

    
24.08.2016 / 15:25