无法读取未定义的属性

无法读取未定义的属性

本文介绍了无法读取未定义的属性“navCtrl"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For hours I've been searching for a solution to this problem in my project to no avail. I've read many of the other "Cannot read property ... of undefined" posts, but can't seem to find a solution for mine.

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

Below is the relevant code in my project.

这是一个 Ionic 2/Apache Cordova 项目,下面的页面是应用程序的登录页面.它不是核心应用组件之一,它只是一个普通页面.

This is an Ionic 2 / Apache Cordova project and the page below is the Sign In Page for the app. It is not one of the core app components, it is simply a regular page.

出于某种原因,在 onSignIn() 方法中无法识别 NavController,但我不知道为什么.我已经在构造函数中注入了 NavController,看起来我没有按照我知道的任何已知程序进行操作,但它每次仍然失败.

For some reason, the NavController is not being recognized in the onSignIn() method, but I have no idea why. I've injected NavController in the constructor, and it doesn't look like I am failing to follow any known procedure that I am aware of, but it's still failing every time.

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

推荐答案

解决此问题的更好方法是使用 箭头函数:

A better way to solve this issue would be by using arrow functions:

箭头函数表达式的语法比函数短表达式并且不绑定它自己的 this、arguments、super 或新目标.

所以你的问题可以通过像这样改变 onSignIn 方法来解决:

So your issue would be solved by just changing the onSignIn method like this:

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

这篇关于无法读取未定义的属性“navCtrl"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 15:00