Ionic - How to store the session token as a global (for the application) accessible variable?

I know I can use localstorage or SQLite, but I'm not sure how to do this.

In my application, I get a session token in the login controller, where I make a mail request to the server and get a session token in return.

I am not sure how to make this marker available around the world.

PS: I am very new to AngularJs.

+5
source share
1 answer

in your controller after receiving the token from the server

$scope.token = token; 

you can say

 localStorage.setItem("token", $scope.token); 

then when you want to get a token (say, in another controller), all you have to say is

 $scope.token = localStorage.getItem("token"); 

Also, if they open the application again, you can even check if they have a token

 if(localStorage.getItem("token") !== null && localStorage.getItem("token") !== ""){//go ahead and authenticate them without getting a new token.} 

Also keep in mind that when you log out, if you want to clear the token, you can simply set

 localStorage.setItem("token", ""); 

but keep in mind that you can only set local storage on strings, not boolean or null.

+19
source

All Articles