How to fix push not found in Navcontroller

I am getting the following error while using this code. I have also tried to change the push function to setRoot and the same error still persists.

I want to navigate to the home page which is the login page in case the user is not signed in but unable to do so.

The console shows that it entered the if statement but the navctrl command is not getting executed.

MyApp_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property ‘push’ of undefined

import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController} from 'ionic-angular';
import * as firebase from 'firebase/app';
import { HomePage } from '../home/home';

/**
 * Generated class for the MainPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

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

export class MainPage {



  constructor(public navParams: NavParams, public alertCtrl: AlertController, public navController:NavController) {

  }

  ionViewDidLoad() {

    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        console.log(user);
        console.log('entered in if');
        // User is signed in.
      } else {
        console.log(user);
        console.log('entered in else');
        this.navController.push(HomePage);

        // No user is signed in.
      }
    });

    console.log('ionViewDidLoad MainPage')


  }

}

Hello,
I do not use firebase, so it is only a guess.
My guess is, that this has changed his scope inside your call of onAuth… If this is so, then this is different to that this you would await this time. This is complicated.

Declare out side of them:
let that = this;
and use that inside.

Or as @rapropos would say: Never use function inside, use fat arrow. This should preserve this.

firebase.auth().onAuthStateChanged(user => {...

Best regards, anna-liebt.

1 Like

This worked, thank you so much. I had been stuck on this for almost a day.