Angular 4 + Firebase在请求数据库

时间:2017-08-13 10:31:14

标签: angular typescript firebase firebase-realtime-database angularfire2

我试图从Firebase数据库中获取项目,但看起来我无法做到。 运营商"这个"不在快照功能中工作(在this.authState.prenom = snapshot.val().prenom行上)

如果我在函数之外执行它,它似乎在函数之前执行,因此属性为空。我找到的唯一解决方案就是暂停(setTimeout( () => this.authState.prenom = prenom,1000)"行,但不是我想要的。

我只是希望在快照功能结束后执行声明this.authState.prenom = prenom;,或者以任何方式从该快照功能中获取值。

这是我的文件(变量都声明了)

auth.service.ts 这是构造函数:

  constructor(private afAuth: AngularFireAuth,
  private db: AngularFireDatabase,
  private router:Router) {

this.afAuth.authState.subscribe((auth) => {
  this.authState = auth;

  if(this.currentUser){
    var userId = this.currentUser.uid;

    var prenom: any;
    var nom: any;

    firebase.database().ref('/users/' + userId).on('value',function(snapshot) {
      // this.authState.prenom = snapshot.val().prenom; <= This is not working because I can't use "this" operator here and don't know why

      console.log(snapshot.val().prenom);
      console.log(snapshot.val().nom);

      prenom = snapshot.val().prenom;
      nom = snapshot.val().nom;

      // this.authState.nom = snapshot.val().nom; <= not working because of the operator "this"
    });
    this.authState.prenom = prenom // <= Not working because it's executed before the snapshot function and don't know why
    setTimeout( () => this.authState.prenom = prenom,1000); // <= This is working but setting timeout is not a good thing..
    setTimeout( () => this.authState.nom = nom,1000);
    // console.log(this.authState.prenom);
  }
}

1 个答案:

答案 0 :(得分:2)

要使this正常工作,请使用胖箭头函数表示法(与auth.subscribe一样):

firebase.database().ref('/users/' + userId).on('value', (snapshot) => {
  this.authState.prenom = snapshot.val().prenom;
  this.authState.nom = snapshot.val().nom;
});

更多老派替代方案:

var that = this; // capture the correct this in a variable
firebase.database().ref('/users/' + userId).on('value', function(snapshot) {
  that.authState.prenom = snapshot.val().prenom;
  that.authState.nom = snapshot.val().nom;
});

或者:

firebase.database().ref('/users/' + userId).on('value', function(snapshot) {
  this.authState.prenom = snapshot.val().prenom;
  this.authState.nom = snapshot.val().nom;
}, this); // pass in the this as the last parameter

有关详细信息,我强烈建议您阅读How to access the correct `this` inside a callback?