在角度js中,如何存储变量以用于其他http函数

时间:2016-09-10 20:45:27

标签: javascript angularjs oauth

我有以下控制器:

angular.
  module('phoneList').
  component('phoneList', {
    templateUrl: '/phone-list.template.html',
    controller: ['$http',
      function PhoneListController($http) {
        var self = this;

        var access_token = '';



          var data = $.param({
              grant_type: 'password',
              username: 'test',
              password: 'test',
              client_id:'1234',
              client_secret:'12345',
          });

          var config = {
              headers : {
                  'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
              }
          }

          $http.post('/o/token/', data, config)
          .success(function (data, status, headers, config) {
              self.access_token = data['access_token'];
              console.log(access_token);
          })
          .error(function (data, status, header, config) {
              $scope.ResponseDetails = "Data: " + data +
                  "<hr />status: " + status +
                  "<hr />headers: " + header +
                  "<hr />config: " + config;
          });


          var header = {
                  headers : {
                      'Authorization': 'Bearer '+self.access_token
                  }
              }

        $http({method: 'GET', url: 'api/posts/', headers: {'Authorization': 'Bearer '+self.access_token}}).then(function(response) {
          self.phones = response.data;

        });
      }
    ]
  });

我想使用从此函数返回的访问令牌,持续数天。我不想每次都获得一个新令牌,但确定令牌是否已过期或是否需要检索令牌:

$http.post('/o/token/', data, config)
          .success(function (data, status, headers, config) {
              self.access_token = data['access_token'];
              console.log(access_token);
          })

在我的get函数中:

$http({method: 'GET', url: 'api/posts/', headers: {'Authorization': 'Bearer '+self.access_token}}).then(function(response) {
          self.phones = response.data;

        });

我如何做到这一点?

1 个答案:

答案 0 :(得分:0)

假设您的应用名称为myapp。 然后,创建一个名为authentication的模块,您可以在其中放置一个工厂,该工厂将检索该令牌并将其放入会话存储中。在同一工厂中,您可以添加将返回会话存储数据的getToken服务:

angular.module('authentication').factory('authenticationService', function($http, $se){
    function authenticate(){
        $http.post('/o/token/', data, config)
              .success(function (data, status, headers, config) {
                  $sessionStorage.access_token = data['access_token'];
              });
    }    
    function getToken(){
        return $sessionStorage.access_token;
    }
    return {
        authenticate:authenticate,
        getToken:getToken
    };
});

在主模块中,调用run函数并调用您的服务:

angular.module('myapp').run(function(authenticationService){
    authenticationService.authenticate().then(function(){
    // Redirection to the next route
    });    
});

在您的控制器中,只需注入authenticationService工厂并使用authenticationService.getToken()检索令牌,而不是执行Ajax调用:

$http({method: 'GET', url: 'api/posts/', headers: {'Authorization': 'Bearer '+ authenticationService.getToken()}}).then(function(response) {
    self.phones = response.data;
});