且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ionic - 如何将会话令牌存储为全局(对于app)可访问变量?

更新时间:2021-12-06 00:26:51

一次在你的控制器中你从服务器获得令牌

in your controller once you get the token from the server

$scope.token = token;

你可以说

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

然后当你想要获取令牌时(比如在另一个控制器中)你只需要说

then when you want to fetch the token (say in another controller) all you have to say is

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

此外,如果他们重新打开应用程序,你甚至可以查看他们是否已经拥有令牌

Also if they re-open the app you can even check to see if they already have a token

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

请注意,在注销时如果要清除令牌,您只需设置

Also be aware that on logout if you want to clear the token you can just set

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

但请注意,您只能将本地存储设置为字符串,而不是布尔值或null。

but be aware you can only set local storage to strings, not booleans or null.