javascript - 在 Promise.catch 中调用函数是未定义的

标签 javascript

尝试从 Promise.catch 中调用函数来处理错误情况,但我不确定如何构造它以避免获得 undefined reference

目标是调用异步登录()函数,如果密码无效,则向用户显示一条消息

// Log in user
login(email, password){
//send login request to firebase
  this.af.auth.login(
    {
      email: email,
      password: password
    },
    {
      provider: AuthProviders.Password,
      method: AuthMethods.Password,
    }
  ).then(function(){
    console.log('Success');
  })
  .catch(function(error){
    this.showLoginErrorWindow(error);
  );
}

// Display error message to user 
// ** This function never gets called **
showLoginErrorWindow(message){
    console.log('message: ' + message);
    this.loginErrorMessage = 'Invalid email or password';
    this.showLoginError = true;    //Angular
}

给我错误:

TypeError: Cannot read property 'showLoginErrorWindow' of null

最佳答案

只需将 current 添加到方法中并根据需要使用它。这是我每次都会做的链接黑客。

// Log in user
login(email, password){
//send login request to firebase
var current = this;
  this.af.auth.login(
    {
      email: email,
      password: password
    },
    {
      provider: AuthProviders.Password,
      method: AuthMethods.Password,
    }
  ).then(function(){
    console.log('Success');
  })
  .catch(function(error){
    current.showLoginErrorWindow(error);
  );
}

// Display error message to user 
// ** This function never gets called **
showLoginErrorWindow(message){
    console.log('message: ' + message);
    this.loginErrorMessage = 'Invalid email or password';
    this.showLoginError = true;    //Angular
}

这可能是我做的,如果我错了,请告诉我。

关于javascript - 在 Promise.catch 中调用函数是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42537338/

相关文章:

javascript - 如何在没有ID的情况下标记循环生成的复选框?

javascript - stringByEvaluatingJavaScriptFromString,查找特定的输入标签

javascript - 在 jQuery.load() 上对容器的高度进行动画处理

javascript - 如何在 sweet alert 中将选中的复选框属性更改为 true 或 false

javascript - Adobe After Effects 扩展脚本 - 如何从命令行运行脚本并传入参数?

javascript - 使用鼠标滚轮滚动部分

javascript - 最好将图像文件作为数据 URI 或二进制形式数据从浏览器上传到服务器?

JavaScript 日期数组

javascript - 使用 javascript 从字符串原型(prototype)返回值

javascript - AngularJS - 图片 "onload"事件