George
George

Reputation: 75

Angular2 / Ionic2 navigating between pages

I'm having some real issues navigating between pages with Angular2 / Ionic2

If I try and push to a new page using the following code:

import {Page, NavController} from 'ionic-angular';
import {HomePage} from '../home/home';

@Page({
  templateUrl: 'build/pages/login/login.html'
})

export class LoginPage {
  static get parameters() {
    return [[NavController]];
  }

  constructor(nav) {
    this.nav = nav;
  }

  goHome() {
    this.nav.push(HomePage);
  }
}

I receive an error stating:

"push" is not a function

If I try a different tact and try and set homepage as the root like so:

import {IonicApp, Page, NavController} from 'ionic-angular';
import {HomePage} from '../home/home';

@Page({
  templateUrl: 'build/pages/login/login.html'
})
export class LoginPage {
  static get parameters() {
    return [[IonicApp], [NavController]];
  }

  constructor(app, nav) {
    this.app = app;
    this.nav = nav;
  }

  goHome() {
    let nav = this.app.getComponent('nav');
    nav.setRoot(HomePage);
  }
}

I receive an error stating:

"app" is not defined

Please could somebody give me some pointers? Thanks in advance

Upvotes: 1

Views: 583

Answers (1)

Will.Harris
Will.Harris

Reputation: 4014

What I think is going wrong is you aren't declaring app and nav as variables inside the class, so when you assign them in the constructor this.app and this.nav don't actually exist giving you the undefined error.

I see two options to get around this...

Option 1

In the constructor define the app and nav parameters as public or private and this will automatically create the variable in the class for you (this is the common option when dealing with imported classes). An example would be:

export class LoginPage {
  static get parameters() {
    return [[NavController]];
  }

  constructor(public nav) { }

  goHome() {
    this.nav.push(HomePage);
  }
}

Option 2

Define variables in the class before the constructor method (this is more common for your own custom variables especially using a model class). An example of this would be:

export class LoginPage {
  customVariable: string;

  static get parameters() {
    return [[NavController]];
  }

  constructor(public nav) {
    this.customVariable = "test string";
  }

  goHome() {
    this.nav.push(HomePage);
  }
}

Hope this helps and you understand the different uses.

Upvotes: 0

Related Questions