1

I am trying to navigate to another page after user is authenticated with angularfire. Everything works except navigating to another page.

Here is my code:

  constructor(public navCtrl: NavController, public menu: MenuController, public afAuth: AngularFireAuth, public db: AngularFireDatabase, private platform  : Platform) {
    this.navigateIfUserIsLogdIn();
  }

  navigateIfUserIsLogdIn(){
        this.authState = this.afAuth.authState;
        this.user = this.afAuth.auth.currentUser;

        this.afAuth.auth.onAuthStateChanged(function(user) {
          if (user) {
            // User is signed in.
            this.navCtrl.setRoot(HomePage);
          } else {
            // No user is signed in.
          }
        });
  }

The error I get is:

Error: Uncaught (in promise): TypeError: Cannot read property 'navCtrl' of undefined

Why wont it work when inside navigateIfUserIsLogdIn() ?

please help, and provide an example :)

sebaferreras
  • 44,206
  • 11
  • 116
  • 134
Christer
  • 2,746
  • 3
  • 31
  • 50
  • Possible duplicate of [Javascript "this" pointer within nested function](https://stackoverflow.com/questions/9644044/javascript-this-pointer-within-nested-function) – Aluan Haddad Jun 01 '17 at 21:39

2 Answers2

2

You need to use arrow functions like this:

navigateIfUserIsLogdIn(){
    this.authState = this.afAuth.authState;
    this.user = this.afAuth.auth.currentUser;

    this.afAuth.auth.onAuthStateChanged((user) => {
      if (user) {
        // User is signed in.
        this.navCtrl.setRoot(HomePage);
      } else {
        // No user is signed in.
      }
    });
}

Notice that now we do

this.afAuth.auth.onAuthStateChanged((user) => {...});

instead of

this.afAuth.auth.onAuthStateChanged(function(user) {

By using arrow functions, the this property is not overwritten and still references the component instance (otherwise, the this keyword points to the inner function, and navCtrl is not defined in it).

sebaferreras
  • 44,206
  • 11
  • 116
  • 134
-2

try to do that

     constructor(public navCtrl: NavController, public menu: MenuController, public afAuth: AngularFireAuth, public db: AngularFireDatabase, private platform  : Platform) {
    this.navigateIfUserIsLogdIn();
  }

  navigateIfUserIsLogdIn(){
        this.authState = this.afAuth.authState;
        this.user = this.afAuth.auth.currentUser;
        var that= this;
        this.afAuth.auth.onAuthStateChanged(function(user) {
          if (user) {
            // User is signed in.
            that.navCtrl.setRoot(HomePage);
          } else {
            // No user is signed in.
          }
        });
  }
Manspof
  • 598
  • 26
  • 81
  • 173