Nav undefined on first page


#1

Hi,
I’m trying to fork the interaction on first page load: if user is authenticated then he goes to a sidenav menu page, else he goes to a login page, here’s the code:

import { Component, ViewChild } from '@angular/core';
import { Nav } from 'ionic-angular';
import { UserLoginService, LoggedInCallback } from '../services/cognito.service';
import { LoginPage } from '../pages/login/login';
import { MenuPage } from '../pages/menu/menu';

@Component({
    template: '<ion-nav [root]="rootPage" scrollbar-y-auto></ion-nav>'
})
export class MyApp {
    @ViewChild(Nav) private nav: Nav;
    rootPage: any;

    constructor(public userService: UserLoginService) {
        this.goToRootPage();
    }

    private goToRootPage() {
        this.userService.isAuthenticated({
            isLoggedInCallback: function (message, loggedIn) {
                if (loggedIn) {
                    this.nav.setRoot(MenuPage);
                }
                else {
                    this.nav.setRoot(LoginPage);
                }
            }
        });
    }
}

this.nav is undefined, how can I navigate to LoginPage or MenuPage?


#2

Have not understood javascripts this context completely yet, but maybe you can use an arrow function here:

private goToRootPage() {
        this.userService.isAuthenticated({
            isLoggedInCallback: (message, loggedIn) => {
                if (loggedIn) {
                    this.nav.setRoot(MenuPage);
                }
                else {
                    this.nav.setRoot(LoginPage);
                }
            }
        });
    }

Or can you change the UserService to accept a function as parameter instead of an object?


#3

That code executes fine, when it reaches the this.nav it says undefined. It’s unrelated to UserService.


#4

try and put a #nav inside the <ion-nav> tag
and then @ViewChild(“nav”) private nav:Nav;


#5

try this code, then you maybe understand:

let color = 'red';
let myObject = {
    color: 'blue',
    myFunction: function () {
        console.log('Function: ' + this.color)
    },
    myArrowFunction: () => {
        console.log('ArrowFunction: ' + this.color)
    }
}
myObject.myFunction();
myObject.myArrowFunction();

The Function binds this to the object, the Arrow Function binds this to the color variable outside the object. Same is with your this.nav


#6

Thanks @Nexi! So the function removed this.nav from the scope correct? I used an arrow function and it worked.