首页 文章

Ionic 3组件,运行时错误:无法读取undefined(nav)的属性“push”

提问于
浏览
0

我为Ionic 3 App创建了一个侧边栏组件 . 我希望在其上有动态填充的按钮,以推送不同的页面 . 然而,无论我做什么,当我点击侧边栏中的一个按钮时,Ionic会给出一个错误:“运行时错误:无法读取属性”推送“未定义” . 我正在导入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

    你需要使用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/

  • 0

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

    在你的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 }>;
    
    constructor() {
    
    this.pages = [
    {title:'Dashboard', component: HomePage, icon:'home'}
    ];
    
    }
    
    openPage(page) {
    this.nav.push(LoginPage);
    }
    
    }
    

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

相关问题