2017-04-14 20 views
3

幾個小時來,我一直在尋找解決方案,在我的項目中這個問題無濟於事。我讀過很多其他的「無法讀取屬性...的未定義」的帖子,但似乎無法找到我的解決方案。無法讀取未定義的屬性'navCtrl'

下面是我的項目中的相關代碼。

這是一個Ionic 2/Apache Cordova項目,下面的頁面是應用程序的登錄頁面。它不是核心應用程序組件之一,它只是一個常規頁面。

出於某種原因,NavController在onSignIn()方法中未被識別,但我不知道爲什麼。我在構造函數中注入了NavController,它看起來並不像我沒有遵循任何我知道的已知過程,但它仍然每次都失敗。

import firebase from 'firebase'; 
import { Component } from '@angular/core'; 
import { NavController, NavParams } from 'ionic-angular'; 
import { HomePage } from './../home/home'; 

var provider = new firebase.auth.FacebookAuthProvider(); 

@Component({ 
    selector: 'page-signin', 
    templateUrl: 'signin.html', 
}) 

export class SignInPage { 

    constructor(public navCtrl: NavController, public params: NavParams) {} 

    onSignIn() { 
    firebase.auth().signInWithPopup(provider).then(function(result) { 
     console.log(result.credential.accessToken); 
     console.log(result.user.displayName); 
     this.navCtrl.setRoot(HomePage); 
    }).catch(function(error) { 
     console.log(error.message); 
    }); 
    } 
} 

回答

4

一個更好的辦法來解決這個問題是通過使用arrow functions

箭頭函數表達式具有比功能 表達較短的語法和不綁定自己的這一點,參數,超,或 new.target。

所以,你的問題將通過只是改變了onSignIn方法這樣解決:

onSignIn() { 
    firebase.auth().signInWithPopup(provider).then((result) => { 
     console.log(result.credential.accessToken); 
     console.log(result.user.displayName); 
     this.navCtrl.setRoot(HomePage); 
    }).catch(function(error) { 
     console.log(error.message); 
    }); 
    } 

通知的(result) => {...}代替function(result) {...}

+1

是的,這是最好的解決方案。謝謝你的信息:) – Sampath

+1

謝謝!我還沒有嘗試過,但這看起來好多了! –

+1

我完成了您的解決方案的實施,並且我可以確認它完美地工作。謝謝您的幫助! –

1

嘗試像下面的代碼:

let _this; 

@Component({ 
    selector: 'page-signin', 
    templateUrl: 'signin.html', 
}) 

export class SignInPage { 

    constructor(public navCtrl: NavController, public params: NavParams) { 
    _this = this; //Either here or in onSignIn whichever called first 
    } 

    onSignIn() { 
    _this = this; //Either here or in constructor whichever called first 
    firebase.auth().signInWithPopup(provider).then(function(result) { 
     console.log(result.credential.accessToken); 
     console.log(result.user.displayName); 
     _this.navCtrl.setRoot(HomePage); 
    }).catch(function(error) { 
     console.log(error.message); 
    }); 
    } 
} 

我認爲你正面臨因爲this範圍的問題。在你的案例範圍this屬於then內部傳遞的函數。

+0

是的!這工作完美!非常感謝你! –

相關問題