1

I need do this:

  async doLogin(user: User) {
    try {
      const result = await this.AngularFireAuth.auth.signInWithEmailAndPassword(user.email, user.password);
      if (result) {
        this.AngularFireAuth.authState.subscribe(user => {
          if (user) {
            var ref = firebase.database().ref(`profile/${user.uid}`);
            ref.once("value")
              .then(function(snapshot) {
                var key = snapshot.key;
                if (user.uid === key) {
                  this.navCtrl.setRoot(HomePage);
                }
                else {
                  this.navCtrl.setRoot(ProfilePage);
                }
              });
          }
        });
      }
    }
    catch (error) {
      let toast = this.toastCtrl.create({
        message: this.loginErrorString,
        duration: 3000,
        position: 'top'
      });
      toast.present();
    }
  }

But i got this error: TypeError: Cannot read property 'navCtrl' of undefined

I don't know why it does it but i think that the method doLogin can't read the module navCtrl. The navCtrl method was add to construct obviously.

Best Regards friends

ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56
Matias Celiz
  • 322
  • 3
  • 11
  • 1
    Change `.then(function(snapshot) {` to an arrow function. `function` keyword creates a new `this` context – dbandstra Sep 20 '17 at 19:23

1 Answers1

1

First, try to use arrow functions (snapshot) => {...} instead of regular function(snapshot) {...}. In your case you're using this keyword, so there are many issues with old functions, which were solved in new ES6 arrow functions!

For more info about arrow functions and this: https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4

P.S.
  • 15,970
  • 14
  • 62
  • 86