can't access NavController from method

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 :)


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).


尝试做到这一点

     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.
          }
        });
  }
链接地址: http://www.djcxy.com/p/94916.html

上一篇: 执行上下文和((this object))

下一篇: 不能从方法访问NavController