【问题标题】:in angular js, how to store variable for use in other http functions在 Angular js 中,如何存储变量以用于其他 http 函数
【发布时间】:2016-09-11 05:20:28
【问题描述】:

我有以下控制器:

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;

        });

我该如何做到这一点?

【问题讨论】:

    标签: javascript angularjs oauth


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-11-10
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      相关资源
      最近更新 更多