我有一个服务,它在/src/main.ts:上获取一个验证身份验证状态的令牌
if (TokenService.getAccessToken() !== undefined) {
...
}
token.service.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 };
storage.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
我只得到未定义,但当在存储区内使用console.log((时,我得到了值,但在应用程序启动后。
我还使用这个函数在/router/index.ts中创建一个条件当我使用localStorage时,我得到了很好的值。
我的依赖项:
"@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",
我能做什么?谢谢
我发现您的令牌.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) {
...
}