Run code before starting services - Angularjs

Asked

Viewed 35 times

1

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

Because I want to use the function $http.defaults.headers before starting the services so that I can instantiate the header in all services I request, but it seems that it loads all the code and then returns it 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.

2 answers

1

What you need is to create an Interceptor using the $httpProvider.

Maybe this link will help you Interceptor

1

You can implement a Interceptor exclusively for the service $http, and manipulate 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: http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.