0

I have a function within my page component and once its executes, it will check if email exists in Firebase database or not. If yes, I want to display an alert controller showing the error message.

For some reason I am unable to do so because of an error I am getting. Code is below:

doRegister(){
    this.fbAuth.auth.createUserWithEmailAndPassword(this.email, this.password).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        //console.log(error);
        if(errorCode == "auth/email-already-in-use"){
            let alert = this.alertCtrl.create({
                title: 'Low battery',
                subTitle: '10% of battery remaining',
                buttons: ['Dismiss']
             });
             alert.present();
        }
    });           
}

and the error I am getting upon entering an email and submitting the form:

> core.js:1350 
ERROR TypeError: Cannot read property 'alertCtrl' of
> undefined
>     at registration.ts:34
>     at e.b (auth.js:23)
>     at Yb (auth.js:26)
>     at Ub (auth.js:26)
>     at z.h.Qb (auth.js:25)
>     at Cb (auth.js:19)
>     at t.invoke (polyfills.js:3)
>     at Object.onInvoke (core.js:4629)
>     at t.invoke (polyfills.js:3)
>     at r.run (polyfills.js:3)

Am I missing something here? I am literally using the same code available on Ionic official documentation to generate the alert.

The link is here: Ionic Documentation for Alert Controller

Note: I am using Ionic version 3.19.1

Striped
  • 2,544
  • 3
  • 25
  • 31
ksa_coder
  • 1,393
  • 3
  • 15
  • 38

1 Answers1

1

When you're inside a callback function this refers to something else than you may expect. Inside the callback this is the function that you're in, not the context from which it was called.

There are many ways to ensure you can still call functions on the original context. Probably the simplest one is to give the original this another name:

doRegister(){
   var self = this;
   this.fbAuth.auth.createUserWithEmailAndPassword(this.email, this.password).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    //console.log(error);
    if(errorCode == "auth/email-already-in-use"){
      let alert = self.alertCtrl.create({
        title: 'Low battery',
        subTitle: '10% of battery remaining',
        buttons: ['Dismiss']
      });
      alert.present();
    }

  });           
}

For a much longer explanation on this problem, see How to access the correct `this` inside a callback?. The accepted answer there also contains some of the other common solutions for the problem.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks a lot mate...that worked fine! It's good to know the difference from now on...will do additional reading. – ksa_coder Feb 11 '18 at 00:20