【问题标题】:Access this in Firebase Angular2 promise在 Firebase Angular2 承诺中访问它
【发布时间】:2016-12-05 16:55:22
【问题描述】:

我正在使用 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 中很烦人,我找不到让我的脚本正常工作的方法。

【问题讨论】:

    标签: angular typescript firebase firebase-authentication es6-promise


    【解决方案1】:

    如果您使用箭头函数,它将保留 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');
        }
    });
    

    【讨论】:

    • 感谢它按预期工作......必须提高我的打字技能。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-29
      • 2016-07-25
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      相关资源
      最近更新 更多