简体   繁体   中英

this.nav is undefined - Ionic2

I'm having a problem with this piece of code here:

import { Component, ViewChild } from '@angular/core';
import { Nav, NavParams } from 'ionic-angular';
import { Page1 } from '../page1/page1';
import { Page2 } from '../page2/page2';
import { Login } from '../auth/login/login';
@Component({
    templateUrl: 'home.html'
})
export class Home {
    @ViewChild(Nav) nav: Nav;
    rootHomePage: any = Page1;
    pages: Array<{title: string, action: any}>;
    user = this.navPrm.get('auth').current_user();
    constructor(public navPrm: NavParams) {
        console.log("TesteTesteTesteTesteTesteTesteTesteTesteTeste");
        console.log(this.nav);
        // used for an example of ngFor and navigation
        this.pages = [
            { title: 'Page One', action: this.openPage(Page1) },
            { title: 'Page Two', action: this.openPage(Page2) },
            { title: 'Logout', action: this.user.logout() }
        ];
    }
    openPage(page) {
        // Reset the content nav to have just this page
        // we wouldn't want the back button to show in this scenario
        this.nav.setRoot(page);
    }
}

So, on the openPage() method, the this.nav (the nav is declared above) is returning an error: this.nav is undefined. Someone has any idea why?

Try this.nav.rootNav.setRoot(page) . This should work. It works for me.

One more thing, isn't user = this.navPrm.get('auth').current_user(); is supposed to be inside the constructor when you are retrieving the value from navParam . (Since, I am not familiar with your code, not sure about this part though. Just seemed wrong.)

使用try and catch

try{} catch(e) { console.error(e); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM