【问题标题】:Angularfire2 email authentication referencing variables outside of promiseAngularfire2电子邮件身份验证引用承诺之外的变量
【发布时间】:2016-05-17 15:14:58
【问题描述】:

我有这个组件:

export class LoginComponent {
  login_error = "";

  constructor(public af: AngularFire) {
    this.af.auth.subscribe(auth => console.log(auth));
  }

  login(credentials) {
      this.af.auth.login({ email: credentials.email, password: credentials.password})
      .catch(function (error) {
        switch (error.code) {
          case "INVALID_USER":
            console.log("Invalid email");
            this.login_error = "Email is invalid"; //<----- broken
            break;

          case "INVALID_PASSWORD":
            console.log("Invalid password");
            this.login_error = "Password is invalid"; //<----- broken
            break;

          default:
            break;   
        }
      });
  }

  logout(){
    this.af.auth.logout();
  }
}

我希望能够设置模板中使用的 login_error 变量(在 .catch 中),以通知用户他们的电子邮件或密码不正确,但我无法引用 Promise 之外的变量。我做错了什么还是有更好的方法来做我想要实现的目标?

【问题讨论】:

    标签: authentication typescript angular promise angularfire


    【解决方案1】:

    我会改用箭头函数。因此,您将能够使用上下文 this(此处的组件实例):

    login(credentials) {
      this.af.auth.login({ email: credentials.email, password: credentials.password})
      .catch((error) => { // <-------
        switch (error.code) {
          case "INVALID_USER":
            console.log("Invalid email");
            this.login_error = "Email is invalid";
            break;
    
          case "INVALID_PASSWORD":
            console.log("Invalid password");
            this.login_error = "Password is invalid";
            break;
    
          default:
            break;   
        }
      });
    }
    

    【讨论】:

    • 当我看到解决方案如此简单时,我笑了。这确实奏效了。我肯定有更多关于 ES6 和 JS 的知识要学习。谢谢蒂埃里!
    猜你喜欢
    • 2017-06-16
    • 2018-02-10
    • 2023-03-18
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    相关资源
    最近更新 更多