Ionic 2 Angular 2 - 无法从方法访问 NavController

Ionic 2 Angular 2 - can't access NavController from method

我正在尝试在用户通过 angularfire 进行身份验证后导航到另一个页面。除了导航到另一个页面外,一切正常。

这是我的代码:

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

我得到的错误是:

错误:未捕获(承诺):类型错误:无法读取未定义的 属性'navCtrl'

为什么它在 navigateIfUserIsLogdIn() 内部时不起作用?

请帮忙,并提供一个例子:)

尝试这样做

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

你需要像这样使用箭头函数:

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

注意现在我们做

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

而不是

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

通过使用箭头函数,this 属性 不会被覆盖并且仍然引用组件实例(否则,this 关键字指向内部函数,navCtrl里面没有定义。