Cannot read property "navCtrl" undefined

For hours I have searched for a solution to this problem in my project to no avail. I have read many other posts "Can't read property ... from undefined" but cannot 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 application login page. This is not one of the main components of the application, it is just a regular page.

For some reason the NavController is not recognized in the onSignIn () method, but I have no idea why. I injected the NavController constructor into the constructor and it doesn't seem like I am not doing any known procedure that I know of, but it still fails 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);
    });
  }
}

      

+3


source to share


2 answers


The best way to solve this problem would be to use arrow functions :

An arrow function expression has a shorter syntax than a function expression and does not bind its own arguments, super, or new.target.

So your problem will be solved by simply changing the method onSignIn

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

      

Note (result) => {...}

instead offunction(result) {...}

+5


source


try to do below code:

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

      



I think you are facing a problem due to the volume this

. In your case, the scope this

belongs to the function that is being passed internally then

.

+1


source







All Articles