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

时间:2022-08-24 14:48:32

I have the following controller:

我有以下控制器:

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;

        });
      }
    ]
  });

I want to use the access token returned from this function that lasts several days. I don't want to get a new token every time but determine if the token is expired or if another needs to be retrieved:

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

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

In my get function:

在我的get函数中:

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

        });

How do I accomplish this?

我该如何做到这一点?

1 个解决方案

#1


0  

Let's say your app's name is myapp. Then, create a module called authentication where you can put a factory that will retrieve the token and put it in a session storage. In the same factory, you can add a getToken service that will return your session storage 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
    };
});

In your main module, call the the run function and invoke your service :

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

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

In your controller, just inject the authenticationService factory and retrieve the token with the authenticationService.getToken() instead of doing Ajax calls :

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

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

#1


0  

Let's say your app's name is myapp. Then, create a module called authentication where you can put a factory that will retrieve the token and put it in a session storage. In the same factory, you can add a getToken service that will return your session storage 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
    };
});

In your main module, call the the run function and invoke your service :

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

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

In your controller, just inject the authenticationService factory and retrieve the token with the authenticationService.getToken() instead of doing Ajax calls :

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

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