Search code examples
angularjsjwttokenaccess-tokenexpress-jwt

AngularJS - How to store JWT token in $localStorage


I have this service call apiService, in there i can get the token that is generated in the server side.

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

my 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*
}

I have try to put the token in my $localStorage but im getting a inject error because only providers are injectable in configuration blocks.


Solution

  • You dont require to define any module or inject any other module in the application. inject $window in your application and then you can access the localstorage module like this

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

    and then,

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

    and you can retrieve the localStorage value like this

    $window.localStorage.getItem('token');