繁体   English   中英

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

[英]Calling a function within Promise.catch is undefined

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

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

// 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
}

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

我最近遇到了与 firebase API 类似的问题。 我能够通过使用箭头函数而不是 catch 函数中的普通函数来解决它,例如:

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((error)=>{
    current.showLoginErrorWindow(error);
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM