【问题标题】:Angular 4 + Firebase getting the value out of a snapshot when requesting databaseAngular 4 + Firebase 在请求数据库时从快照中获取价值
【发布时间】:2018-01-21 09:35:38
【问题描述】:

我正在尝试从 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);
  }
}

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 非常感谢!胖箭头功能对我来说非常有用:)
    猜你喜欢
    • 2019-03-03
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 2019-05-07
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多