0

I think i deal with some basic thing but dispite that I am not able to solve this alone.

In Angular Documentation I foundout option how to set header for each request. It should be something like:

module.run(function($http) {
  $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
});

This looks find if you know token from start as in this example. But i get user token after he login.

So I try something like:

login: function(email, password) {
    var data = {'userName':email, 'password': password};
    $http.post('api/v1/users/login.php', data).then(function (res) {
        $cookies.put('user', res.data);
        $http.defaults.headers.common.Authorization = 'Bearer '+res.data.token;
    });
}

This now added Authorization header to each request but just inside of LoginCtrl. If I make request in any other controller its without this header.

As soon as I create other $http request in other controllers I need it work there. Is there some nice way how to set it for each controller or I have to set it at load of each controller from cookie?

2 Answers 2

2

Angular provides you with interceptors that can manipulate any $http call from your application. Look at this documentation.

example

appName.config(["$httpProvider", ($httpProvider: ng.IHttpProvider) => {
                $httpProvider.interceptors.push(() => { 

                        return {
                            'request': (config) => {

                           //retrieving a token from localStorage for example
                               var token = localStorage.getItem("token"); 
                               if (token)
                                   config.headers["Authorization"] = "Bearer " + token;

                                return config;
                            },
                            'responseError': (rejection) => {

                            }
                        }
                    }
                );
            }]);
Sign up to request clarification or add additional context in comments.

Comments

0

First you have create Services for every controller

module.run(function($http, $rootScope, subHeaderService) {
  subHeaderService.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  //subHeaderService.auth= 'Basic YmVlcDpib29w'; you can use like this
});

app.service('subHeaderService', function() {
    return {};
});

app.controller('mainCtrl', ['$scope', 'subHeaderService',
    //subHeaderService.auth     
    //call here 
]);

or you can use interceptors.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.