0

enter image description here I am using Angular-satellizer extension for the login/register feature but I am stuck at number 7. I cant save JWT to localStorage. I checked the developer tools in chrome but there is no token.

.controller('loginCtrl', function($scope, $state, $auth, jwtHelper, $window) {
$scope.login = function() {

  $auth.login($scope.user)

    .then(function(response) {

    var gelenToken = response.data;

    var tokenPayload = jwtHelper.decodeToken(gelenToken.token);

    console.log(JSON.stringify(tokenPayload)); // Output:{"sub":"1","iat":1496346513,"exp":1497556113,"data":{"role":"admin"}}

    $window.localStorage.setItem('token', JSON.stringify(tokenPayload));

    $state.go('baba.manga');
    })
};
})
Nasuh
  • 355
  • 3
  • 20
  • 1
    I'm not an Angularjs guy, but I don't think you'd have to use `$window.localStorage`, I think `localStorage` would do fine, unless Angularjs prevents you from accessing global variables. That probably isn't your solution though. – Adam Jun 01 '17 at 21:44
  • Also, do you want to store the decoded token or encoded token? – Ju66ernaut Jun 01 '17 at 21:48
  • You guys right. I can see the token in my developer tools this time. But when i refresh the page its gone again and satellizer does not see the token. – Nasuh Jun 01 '17 at 22:31

2 Answers2

1

I'm using the JWT with Angular 4 and Node JS in the backend. I don't think u need to use $window.

  ......
  data => {  
    localStorage.setItem('token', data.token);
    localStorage.setItem('userId', data.userId);
    this.router.navigateByUrl('/');
  },
  ......

This should work, if not please the link to the plunker/git, I'll take a look.

Mani S
  • 2,501
  • 1
  • 12
  • 12
  • You are right. I can see the token in my developer tools this time. But when i refresh the page its gone again and satellizer does not see the token. – Nasuh Jun 01 '17 at 22:39
1

You can use both :

localStorage.setItem('token', data.token);

or

$window.localStorage.token = JSON.stringify(data.token);

If it's getting deleted on page refresh then you need to check if you have reset the localStorage somewhere or some script is doing it

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66