2016-06-16 4 views
0

몇 가지 기본적인 사항을 다룰 생각이지만이 문제를 해결할 수는 없습니다.각 컨트롤러의 각 요청에 토큰을 추가하는 방법 - 각부

Angular Documentation 각 요청마다 헤더를 설정하는 방법을 알았습니다. 다음과 같은 형식이어야합니다.

이 예에서 처음부터 토큰을 알면 알 수 있습니다. 하지만 그는 로그인 한 후 사용자 토큰을 얻습니다.

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

이 이제 추가 Authorization 각 요청에 헤더하지만 단지 LoginCtrl의 내부 :

그래서 내가 좋아하는 뭔가를하려고합니다. 이 헤더가없는 다른 컨트롤러에서 요청하면

다른 컨트롤러에서 다른 $ http 요청을 만들면 바로 거기에서 작동해야합니다. 각 컨트롤러마다 설정하는 좋은 방법이 있습니까 아니면 쿠키에서 각 컨트롤러의로드시 설정해야합니까?

답변

2

각도는 응용 프로그램에서 $ http 전화를 조작 할 수있는 interceptors을 제공합니다. 이 부분을보세요. documentation.

예를

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) => { 

          } 
         } 
        } 
       ); 
      }]); 
0

먼저 당신은 모든 컨트롤러

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 
]); 

용 서비스를 생성하거나 당신은 인터셉터를 사용할 수 있습니다.

관련 문제