2017-06-01 89 views
1

訪問NavController我想在用戶使用angularfire進行身份驗證後導航到另一個頁面。除了導航到其他頁面之外,一切都可以工作。Ionic 2 Angular 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; 

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

我得到的錯誤是:

錯誤:(在承諾)未捕獲:類型錯誤:無法讀取的不確定

財產 'navCtrl'

爲什麼不工作時,在裏面navigateIfUserIsLogdIn()?

請大家幫忙,並提供了一個例子:)

+0

可能重複[Javascript「this」指針在嵌套函數中](https://stackoverflow.com/questions/9644044/javascript-this-pointer-within-nested-function) –

回答

1

您需要使用箭頭功能是這樣的:

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不限定它)。

+1

Greate答案!謝謝! :) – Christer

+0

很高興幫助:) – sebaferreras

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

至少解釋了原因,並指出使用'=>'的選項。真的,但是,這是一個重複的 –