Typescript error: @viewChild undefined

Typescript error: @viewChild undefined

尝试使用 Ionic Tabs 文档中 tabs.ts 中的 select() 方法。但是似乎当我尝试 运行 时,它说 "select is undefined" 并且当我尝试 console.log(tabs) 时我发现我的 viewChild 实际上是 empty/undefined。尝试搜索 viewChild 未定义的原因,但无法真正理解原因。

Link 至离子标签文档: https://ionicframework.com/docs/api/components/tabs/Tabs/

tabs.html

<ion-tabs #tabs>
  <ion-tab [root]="tab1Root" tabTitle="Request" tabIcon="alert"></ion-tab>
  <ion-tab [root]="tab2Root" [rootParams]="detailParam" tabTitle="Pending" 
   tabIcon="repeat"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="Completed" tabIcon="done-all"></ion-
   tab>
  <ion-tab [root]="tab4Root" tabTitle="Profile" tabIcon="person"></ion-tab>  
</ion-tabs>

tabs.ts

import { Component, ViewChild } from '@angular/core';
import { NavController, NavParams, AlertController, Tabs } from 'ionic-
angular';
import { PendingJobPage } from '../pending-job/pending-job';
import { CompletedJobPage } from '../completed-job/completed-job';
import { RequestPage } from '../request/request';
import { ProfilePage } from '../profile/profile';

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {

  @ViewChild('tabs') tabRef: Tabs;
  pending: any;
  apply: boolean;
  detailsParam: any;

  tab1Root = RequestPage;
  tab2Root = PendingJobPage;
  tab3Root = CompletedJobPage;
  tab4Root = ProfilePage;

  constructor(public navParams: NavParams, public navCtrl: NavController) {
    this.pending = this.navParams.get('param1');
    this.apply = this.navParams.get('apply');
    this.detailsParam = this.navParams.data;
    console.log("a = ", this.tabRef);

    if(this.apply === true){
      this.navCtrl.parent.select(1);
    }
    else{
      this.navCtrl.parent.select(0);
    }
  }
}

就像您在 Angular Docs

中看到的那样

ViewChild is set after the view has been initialized

ViewChild is updated after the view has been checked

export class AfterViewComponent implements  AfterViewChecked, AfterViewInit {

  ngAfterViewInit() {
    // viewChild is set after the view has been initialized <- Here!
  }

  ngAfterViewChecked() {
    // viewChild is updated after the view has been checked <- Here!
  }

  // ...

}

所以你的代码的问题是执行构造函数时视图还没有初始化。您需要将所有与选项卡交互的代码放在 ngAfterViewInit 生命周期挂钩中:

  ngAfterViewInit() {
    // Now you can use the tabs reference
    console.log("a = ", this.tabRef);
  }

如果您只想使用 Ionic 自定义生命周期事件,则需要使用 ionViewDidEnter 挂钩:

export class TabsPage {

@ViewChild('myTabs') tabRef: Tabs;

ionViewDidEnter() {
    // Now you can use the tabs reference
    console.log("a = ", this.tabRef);
 }

}