[英]Ionic Secure Storage get() at the start of the app
我有一个服务,它在 /src/main.ts 中获取一个用于验证 Auth 状态的令牌:
if (TokenService.getAccessToken() !== undefined) {
...
}
令牌服务.ts
import storage from '@/plugins/storage'
const ACCESS_TOKEN_KEY = "access_token";
const TokenService = {
getAccessToken(){
storage.get(ACCESS_TOKEN_KEY).then(v => {
return v
})
},
async saveAccessToken(accessToken: string) {
storage.set(ACCESS_TOKEN_KEY, accessToken);
},
}
export { TokenService };
存储.ts:
import { Storage, Drivers } from '@ionic/storage'
const localStorage = new Storage()
localStorage.create()
const storage = {
set: async(i: any, v: any) => {
await localStorage.set(i, v)
},
get(i: any){
return localStorage.get(i)
},
remove: async (i: any) => {
await localStorage.remove(i);
},
clear: async () => {
await localStorage.clear();
}
}
export default storage
我只是未定义,但是在 storage.ts 中使用 console.log() 时,我得到了值,但是在应用程序启动之后。
当我使用 localStorage 时,我还使用这个 function 在 /router/index.ts 中创建条件,我得到了很好的值。
我的依赖:
"@ionic-native/secure-storage": "^5.31.1",
"@ionic/storage": "^3.0.4",
"@ionic/vue": "^5.6.0-dev.202102221703.5300dcc",
"@ionic/vue-router": "^5.6.0-dev.202102221703.5300dcc",
"vue": "^3.0.0-0",
"vue-router": "^4.0.0-0",
"vuex": "^4.0.0-rc.2",
我能做些什么? 谢谢。!
我在您的token.service.ts中发现了一个问题,您没有返回任何内容: getAccessToken
// async since is returning a promise
async getAccessToken(){
// Returning the promise.
return storage.get(ACCESS_TOKEN_KEY)
}
从外部使用它看起来像这样:
// using await because we want the promise to be solved
if ((await TokenService.getAccessToken()) !== undefined) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.