在 Firebase Angular2 promise 中访问它

Access this in Firebase Angular2 promise

我正在 Angular2 中使用 Firebase,但我无法访问 this

这是我的脚本。对于上下文理解:在登录时,我想检查与该用户相关的数据库中的基本数据是否仍然是最新的。

import { Injectable, Inject } from '@angular/core';
import { AngularFire, AuthProviders, FirebaseAuthState, FirebaseApp } from 'angularfire2';

@Injectable()
export class AuthService {
  user;
  userUID;
  userEmail;
  isAuthenticated: boolean = false;

 constructor(public af: AngularFire, @Inject(FirebaseApp) firebaseApp: firebase.app.App) {
   this.af.auth.subscribe(authState => {
      if (authState && !authState.auth.isAnonymous) {
        this.user = authState;
        this.isAuthenticated = true;
        this.userEmail = this.user.auth.email;
        this.userUID = this.user.auth.uid;

      firebaseApp.database().ref('/users/' + this.userUID).once('value').then(function(snapshot) {
        if (snapshot.val().email !== this.userEmail) { //ERROR HERE
          console.log('update the email in database here');
        }
      });

      console.log('User Logged in', this.user, this.userEmail, this.userUID);
      return;
   }

   this.logout();
   console.log('User Not Authenticated', this.user);
 });
}

错误当然是在我想做这个比较的那一行:

if (snapshot.val().email !== this.userEmail)

我知道 JavaScript/typescript 中的这个很烦人,我找不到让我的脚本正常工作的方法。

如果您使用箭头函数,它将保留 this 所指的内容

firebaseApp.database().ref('/users/' + this.userUID).once('value').then((snapshot) => {
    if (snapshot.val().email !== this.userEmail) {
        console.log('update the email in database here');
    }
});

解决此问题的 JavaScript 标准技巧是预先将 this 保存到变量中,然后使用它,通常是 let self = this。 在 TypeScript 中,当你使用粗箭头函数时,语言会为你做这件事。编译后的 JavaScript 代码将有一个常规函数,但会在函数内部使用一个名为 _this 的变量,该变量预先初始化为 this,而不是 this。 简而言之,不要写 function (param) { // code },而是使用 (param) => { // code }