Ionic - 如何将会话令牌存储为全局(对于应用程序)可访问变量? [英] Ionic - How to store session token as globally (for app) accessible variable?

查看:21
本文介绍了Ionic - 如何将会话令牌存储为全局(对于应用程序)可访问变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用 localstorage 或 SQLite,但我不确定具体如何使用.

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

在我的应用程序中,我在登录控制器中获取会话令牌,在那里我向服务器发出发布请求并作为回报获取会话令牌.

In my app, I'm getting the session token in the Login controller where I make post request to the server and in return get session token.

我不知道如何让这个令牌可以全局访问.

I'm not sure how to make this token globally accessible.

P.S:我对 AngularJs 很陌生.

P.S: I'm very new to AngularJs.

推荐答案

在您从服务器获取令牌后在您的控制器中

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

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

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

更新:我看到人们仍在引用此内容,并希望添加一个警告.在 IOS 上,本地缓存似乎会被操作系统自动清除.我不确定是什么触发了这个,但我遇到了问题,用户丢失了存储在本地存储中的设置.如果这对您来说是个问题,我建议您查看 IndexedDB、pouchdb、sqllite 或其他替代方案.

UPDATE: I see that people are still referencing this, and wanted to add a caveat. On IOS, the local cache seems to be cleared by the OS automatically. I am not sure what triggers this, but I have ran into issues with and users loosing their settings stored in local storage. If that would be an issue for you, I recommend looking at something like IndexedDB, pouchdb, sqllite, or other alternatives.

这篇关于Ionic - 如何将会话令牌存储为全局(对于应用程序)可访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆