1

Attempting to call a function from within a Promise.catch to handle for an error situation, but I'm not sure how to structure it to avoid getting an undefined reference

The goal is call an async login() function and if the password is invalid display a message to the user

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

Gives me the error:

TypeError: Cannot read property 'showLoginErrorWindow' of null
Paul G
  • 314
  • 3
  • 15

2 Answers2

2

Just add current to the method and use it as you want. thats a link hack i do everytime.

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

This is probably me doing it, if i am wrong please let me know.

Smit
  • 2,078
  • 2
  • 17
  • 40
1

I recently got stuck with a similar kind of problem with firebase API. I was able to solve it by using the arrow function rather than the normal ones in the catch function something like:

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);
  );
}
sshashank124
  • 31,495
  • 9
  • 67
  • 76
Suraj
  • 11
  • 3