Ionic 2 Angular 2 - 无法从方法访问导航控制器



我试图在用户通过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.
          }
        });
  }

我遇到的错误是:

错误:undured(在Promise(:typeError:无法读取未定义的

的属性'navctrl'

为什么在navigateifuserislogdin((内部不起作用?

请提供帮助,并提供一个示例:)

您需要使用这样的箭头函数:

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(。

尝试做

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

相关内容

  • 没有找到相关文章

最新更新