【问题标题】:How to store the result of a Firebase query to a variable from a promise?如何将 Firebase 查询的结果存储到 promise 的变量中?
【发布时间】:2016-11-08 17:46:53
【问题描述】:

我是 Angular 新手,但仍在尝试掌握 Promise。

我有一个 ItemDetail 类:

@Component({
  templateUrl: 'build/pages/item-detail/item-detail.html',
  providers: [Auth]
})
export class ItemDetailPage {
  private title;
  private description;
  private author;

  constructor(private navParams: NavParams, private _auth: Auth) {
    this.title = this.navParams.get('item').title;
    this.description = this.navParams.get('item').description;

    _auth.getUser(this.navParams.get('item').author).then(function(snapshot){
      console.log("ayyy lmao = " + JSON.stringify(snapshot.child(navParams.get('item').author).val().email));
      this.author = JSON.stringify(snapshot.child(navParams.get('item').author).val().email);
    });

    console.log("thisAuthor = " + this.author);
    }

}

我正在尝试将从数据库中检索到的电子邮件存储为作者变量。即使它在控制台中正确输出,它的值实际上并没有分配给 Promise 之外的变量。但是,我认为我遇到的问题与承诺有关,这是我仍在努力理解的概念。

Auth类中的getUser方法如下:

  getUser(uid: string): any {
    return firebase.database().ref('/userProfile').orderByKey().equalTo(uid).once("value", function(snapshot){});
  }

如果有更好的方法来做到这一点(没有承诺),那也是一个可靠的选择。

谢谢!

【问题讨论】:

    标签: angularjs ionic-framework firebase firebase-realtime-database ionic2


    【解决方案1】:

    看起来承诺工作正常,但this 指向错误的实例,使用Function.prototype.bindthis 绑定到ItemDetailPage:

    function successHandler(snapshot){ ... };
    
    _auth.getUser(this.navParams.get('item').author).then(successHandler.bind(this));
    

    【讨论】:

    • 非常感谢!你有什么具体的推荐资源来帮助我阅读更多相关信息吗?
    • 对于promise,你可以参考here,对于Angular 2 observable,你可以参考here
    【解决方案2】:

    一些事情......

    获取用户个人资料信息的更好方法是在插入对象时使用uid作为key

    firebase.database().ref('/userProfile/' + uid).once("value", function(snapshot){});
    

    如果您使用=> 胖箭头,绑定已在ionic2 中为您完成

      _auth.getUser(this.navParams.get('item').author)
         .then((snapshot) => {
             // THIS WILL BE WHAT YOU EXPECT...
          });
    

    【讨论】:

      猜你喜欢
      • 2019-12-29
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-24
      • 1970-01-01
      相关资源
      最近更新 更多