【问题标题】:Display data from promise firebase显示来自 promise firebase 的数据
【发布时间】:2019-12-20 11:56:07
【问题描述】:

我有这样的服务

async getBirthdays() {
    const user = await this.authSP.getUserInfo();
    let bdays = [];
    return await new Promise<any>((resolve) => {
    this.angularFire.database.ref("birthdays").orderByChild("creator_user_id").equalTo(user.uid).once("value", (snapshot) => {
        snapshot.forEach(function (childSnapshot) {
          const value = childSnapshot.val();
          value.$key = childSnapshot.key;
          bdays.push(value);
        });
    });

    resolve(bdays);

    });
}

这个承诺返回这个对象数组

在我的组件中,我只是尝试显示头像值:

this.birthdays = await this.birthdaySP.getBirthdays().then(res => {
  var data = res.map(t=>t.avatar);
  console.log(data);
});

但是console.log(data)返回一个空数组。

感谢任何帮助

【问题讨论】:

    标签: javascript firebase ionic-framework firebase-realtime-database promise


    【解决方案1】:

    现在您在once() 回调运行之前调用resolve(bdays),这意味着bdays 只是一个空数组。

    resolve() 的调用需要在bdays 的回调中包含数据:

    async getBirthdays() {
        const user = await this.authSP.getUserInfo();
        let bdays = [];
        return await new Promise<any>((resolve) => {
            this.angularFire.database.ref("birthdays").orderByChild("creator_user_id").equalTo(user.uid).once("value", (snapshot) => {
                snapshot.forEach(function (childSnapshot) {
                  const value = childSnapshot.val();
                  value.$key = childSnapshot.key;
                  bdays.push(value);
                });
                resolve(bdays);
            });    
        });
    }
    

    【讨论】:

      【解决方案2】:

      请您尝试以下方法:

      this.birthdaySP.getBirthdays().then(res => {
        this.birthdays = res.map(t=>t.avatar);
      });
      

      【讨论】:

      • 谢谢。铅是在一次之外的决心
      猜你喜欢
      • 2019-12-25
      • 2021-09-20
      • 2021-06-26
      • 2020-08-01
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多