通过函数调用更改 ionic 2 应用程序中显示的选项卡

Changing the tab shown in an ionic 2 app via a function call

我有一个基于选项卡的 ionic 2 typescript 应用程序。

我想根据用户是否登录更改启动应用程序时显示的默认选项卡。

我尝试使用的代码给我一个错误 _this.tabRef is undefined 我的 app.ts 文件如下所示:

import {Component, ViewChild} from '@angular/core';
import {Platform, ionicBootstrap, NavController, Tabs} from 'ionic-angular';
import {Http, Headers, RequestOptions, HTTP_PROVIDERS, XSRFStrategy, CookieXSRFStrategy} from '@angular/http';
import {StatusBar} from 'ionic-native';
import {HomePage} from './pages/home/home';
import {LoginPage} from './pages/login/login';
import {TabsPage} from './pages/tabs/tabs';
import {DjangoAuth} from './providers/djangoAuth';
import {API_ENDPOINT} from '../app_settings';
import {AUTH_ENDPOINT} from '../app_settings';

@Component({
  template: '<ion-nav [root]="rootPage"></ion-nav>'
})
export class MyApp {
  rootPage: any = HomePage;

  @ViewChild('twipTabs') tabRef: Tabs;

  constructor(public platform: Platform, public djangoAuth: DjangoAuth) {

    this.rootPage = TabsPage;

    platform.ready().then(() => {

      StatusBar.styleDefault();

      djangoAuth.initialize(AUTH_ENDPOINT, false);

      // Check if user is logged in
      djangoAuth.authenticationStatus()
        .then((data:any) => {
            alert('You are logged in');
            // Select the photo upload tab
            this.tabRef.select(2);
          },
          (err:any)=>{
            alert('You are not logged in');
            // Select the login tab
            this.tabRef.select(1);
          });
    });
  }
}

ionicBootstrap(MyApp, [HTTP_PROVIDERS,
  DjangoAuth,
  Tabs,
  {provide:XSRFStrategy, useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken')}]);

我的 tabs.html 看起来像这样:

<ion-tabs #twipTabs>
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Login" tabIcon="information-circle"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="Submit" tabIcon="contacts"></ion-tab>
</ion-tabs>

我的 tabs.ts 看起来像这样:

import {Component, ViewChild, Injectable} from '@angular/core';
import {Tabs} from 'ionic-angular';
import {HomePage} from '../home/home';
import {PhotoPage} from '../photo/photo';
import {LoginPage} from '../login/login';
import {ResetPasswordPage} from '../reset-password/reset-password';

@Component({
  templateUrl: 'build/pages/tabs/tabs.html'
})
@Injectable()
export class TabsPage {

  @ViewChild('twipTabs') tabRef: Tabs;

  private tab1Root: any;
  private tab2Root: any;
  private tab3Root: any;

  constructor() {
    this.tab1Root = HomePage;
    this.tab2Root = LoginPage;
    this.tab3Root = PhotoPage;
  }

}

您可以在选项卡上选择索引而不是视图子项。这将为您省去获取参考文献的麻烦

<ion-tabs [selectedIndex]="selected">

 this.selected = 1;

有关其组件页面的更多信息 http://ionicframework.com/docs/v2/api/components/tabs/Tabs/