Angular 4 + Firebase 在请求数据库时从快照中获取值

Angular 4 + Firebase getting the value out of a snapshot when requesting database

我正在尝试从 Firebase 数据库中取出项目,但我似乎做不到。 运算符 "this" 在快照功能中不起作用(在 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);
  }
}

要使 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?