在angular js中,如何存储变量以供其他HTTP函数使用

in angular js, how to store variable for use in other http functions

本文关键字:变量 其他 HTTP 函数 存储 js angular 何存储      更新时间:2023-09-26

我有以下控制器:

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

我如何完成这个?

假设你的应用程序的名称是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;
});