离子3组件,运行时错误:无法读取未定义的属性“推”(nav)

时间:2018-07-18 15:04:28

标签: angularjs typescript ionic-framework

我为Ionic 3 App创建了一个侧边栏组件。我想在其上动态填充按钮,以推送不同的页面。但是,无论我做什么,当我单击侧栏中的按钮之一时,Ionic都会显示错误消息:“运行时错误:无法读取未定义的属性” push”。 我正在导入Nav,但是当我console.log(this.nav)时,它是未定义的。从字面上看我已经有好几天了。请帮助我...

sidebar.html

<ion-content>
  <ion-list>
    <button ion-button *ngFor="let p of pages" (click)="openPage(p)"> {{p.title}}<ion-icon class="icon" name="{{p.icon}}"></ion-icon></button>
  </ion-list>
</ion-content>

sidebar.ts

import { Component, ViewChild } from '@angular/core';
import { Platform, Nav } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { HomePage } from '../../pages/home/home';
import { LoginPage } from '../../pages/login/login'

@Component({
  selector: 'sidebar',
  templateUrl: 'sidebar.html'
})
export class SidebarComponent {
  @ViewChild(Nav) nav:Nav;

  pages: Array<{ title: string, component: any, icon: any }>;

  pages = [
    {title:'Dashboard', component: HomePage, icon:'home'}
  ];

  constructor() {

  }

  openPage(page) {
    this.nav.push(LoginPage);
  }

}

2 个答案:

答案 0 :(得分:0)

您需要使用NavController而不是Nav来完成您要完成的任务,还需要将其注入到构造函数中才能使这项工作参见以下内容:

import { Component, ViewChild } from '@angular/core';
import { Platform, Nav, NavController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { HomePage } from '../../pages/home/home';
import { LoginPage } from '../../pages/login/login'

@Component({
  selector: 'sidebar',
  templateUrl: 'sidebar.html'
})
export class SidebarComponent {
  @ViewChild(Nav) nav:Nav;

  pages: Array<{ title: string, component: any, icon: any }>;

  pages = [
    {title:'Dashboard', component: HomePage, icon:'home'}
  ];

  constructor(private navCtrl: NavController) {

  }

  openPage(page) {
    this.navCtrl.push(LoginPage);
  }

}

请彻底查看以下文档:https://ionicframework.com/docs/api/navigation/NavController/

答案 1 :(得分:0)

尝试将页面声明放置在构造函数中。

  

在侧边栏。

import { Component, ViewChild } from '@angular/core';
import { Platform, Nav } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { HomePage } from '../../pages/home/home';
import { LoginPage } from '../../pages/login/login'

@Component({
selector: 'sidebar',
templateUrl: 'sidebar.html'
})
export class SidebarComponent {
@ViewChild(Nav) nav:Nav;

pages: Array<{ title: string, component: any, icon: any }>;

constructor() {

this.pages = [
{title:'Dashboard', component: HomePage, icon:'home'}
];

}

openPage(page) {
this.nav.push(LoginPage);
}

}

此外,除非要堆叠页面,否则我建议您改用nav.setRoot()。