首页 文章

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

提问于
浏览
1

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

我得到的错误是:

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

为什么在内部navigateIfUserIsLogdIn()时它不会工作?

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

2 回答

  • 2

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

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

    通过使用箭头函数, the this property is not overwritten and still references the component instance (否则, this 关键字指向内部函数,并且未在其中定义 navCtrl ) .

  • -2

    试着这样做

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

相关问题