AngularJS - 如何在$ localStorage中存储JWT令牌

时间:2018-06-14 16:47:41

标签: angularjs jwt token access-token express-jwt

我有这个服务调用apiService,在那里我可以获得在服务器端生成的令牌。

angular.module('miniMynd')
    .service('apiService', function ($http) {
       return {
         loginUser: function(user){
           $http.post("http://localhost:3010/api/login", user).then(function(response){
             console.log(response.data) * I get the token* 
           })
         },
       }
    });

我的loginCtrl

$scope.login = function(){
  $apiService.loginUser($scope.credentials); * I pass the crendentials to my function on the client side and i receive a token in the service above*
}

我尝试将令牌放在我的$ localStorage中但是我得到了一个注入错误,因为只有提供程序可以在配置块中注入。

1 个答案:

答案 0 :(得分:2)

您不需要在应用程序中定义任何模块或注入任何其他模块。 在您的应用程序中注入$ window,然后您可以像这样访问localstorage模块

angular.module('miniMynd', [])
     .controller('loginCtrl', ['$scope', function ($scope) {
    $apiService.loginUser($scope.credentials);
}]);

然后,

angular.module('miniMynd')
    .service('apiService', function ($http,$window) {
       return {
         loginUser: function(user){
           $http.post("http://localhost:3010/api/login", user).then(function(response){
              $window.localStorage.setItem('token', response.data);
           })
         },
       }
    });

您可以像这样检索localStorage值

$window.localStorage.getItem('token');
相关问题