簡體   English   中英

具有 Ionic 5 和 Angular 10 的區域感知 Promise

[英]Zone Aware Promise with Ionic 5 and Angular 10

我是 Promises(通常使用 Observables)和 Ionic 的新手。

我使用了電容器,我已將用戶 ID 存儲在本地存儲中:

import { Plugins } from '@capacitor/core';

async storeAuthData(token: string, user: IUserAuth): Promise<void>{

    await Plugins.Storage.set({
        key: '_token',
        value: token
    });

    await Plugins.Storage.set({
        key: '_u',
        value: JSON.stringify(user)
    });
}

我想從該存儲集中檢索 userId。 I have wrapped my Promise in a return and believe I've done the correct syntax, but when I call this function I get the Zone Aware Promise _state: null info in the console.

 async getUserId(): Promise<string> {
    return Plugins.Storage
            .get({key: '_u'})
            .then(userObj => {
                var user = JSON.parse(userObj.value);
                return user.id.toString();
            }).catch(err => {
                console.log(err)
                return null;
            });
}

關於如何做到這一點的任何想法?

像這樣調用getUserId函數:

var id = await this.auth.getUserId();
console.log(id)

關於 Promise 的一件事是我們必須將它們包裝在異步方法中。

所以你的代碼會是這樣的:

async storeAuthData(token: string, user: IUserAuth): Promise<void> {
  // now we introduce the await or the code will run out of control
  await Plugins.Storage.set({
    key: '_u',
    value: JSON.stringify(user)
  });

  // same here
  await Plugins.Storage.set({
    key: '_token',
    value: token
  });
}

然后取回

async getUserId(): Promise <string> {
  return Plugins.Storage
    .get({
      key: '_u'
    })
    .then(userObj => JSON.parse(userObj.value))
    .catch(err => {
      console.log(err)
      return null;
    });
}

當我們調用時,我們也必須使用await關鍵字。

像這樣的東西:

console.log('userId', await UserService.getUserId())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM