无法读取未定义的 属性 'navCtrl'

Cannot read property 'navCtrl' of undefined

几个小时以来,我一直在我的项目中寻找解决此问题的方法,但无济于事。我已经阅读了许多其他 "Cannot read property ... of undefined" 帖子,但似乎找不到适合我的解决方案。

下面是我项目中的相关代码。

这是一个 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);
    });
  }
}

试试下面的代码:

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.

内部传递的函数

解决此问题的更好方法是使用 arrow functions:

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or 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) {...}