Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
797 views
in Technique[技术] by (71.8m points)

angular - Cannot read property 'navCtrl' of undefined

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.

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.

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);
    });
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A better way to solve this issue would be by using 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.

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

Notice the (result) => {...} instead of the function(result) {...}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...