来自Ionic docs:
您还可以通过调用select() on 从子组件切换选项卡
使用NavController 实例的父视图。例如,
假设您有一个 TabsPage 组件,您可以调用以下命令
从任何子组件切换到TabsRoot3:
switchTabs() {
this.navCtrl.parent.select(2);
}
因此,一种方法是使用Events。这个想法是在选择侧面菜单中的选项时发布一个事件,并在UserPage 中订阅该事件,然后选择该选项卡作为活动选项卡。
所以,在app.component.ts 文件中的userPage 方法中:
import { Events } from 'ionic-angular';
constructor(public events: Events) {}
userPage(user_id) {
this.events.publish('user:selected', user_id);
}
然后在UserPage 标签页中:
import { Events, NavController } from 'ionic-angular';
constructor(public events: Events, public navCtrl: NavController) {
this.events.subscribe('user:selected', (user_id) => {
// First select this tab if any other tab was selected
this.navCtrl.parent.select(5); // It's the 6th tab, so its index is 5
// Now you can load the data using the user_id, and show it in the view
// ...
});
}
更新
根据您的 cmets,如果尚未创建选项卡,则可能不会发生任何事情(因为我们在构造函数中订阅了事件)。
因此,与其在UserPage 选项卡上订阅该事件,不如让我们尝试使用TabsPage(包含所有子选项卡的那个)。由于我们将使用父选项卡,因此我们需要一个新的共享服务来存储选定的 user_id。因此,创建一个新的共享服务,如下所示:
import {Injectable} from '@angular/core';
@Injectable()
export class ParamService {
public selectedUser: any;
constructor(){ }
}
请将其添加到您的 NgModule 的 providers 数组中(来自您的 app.module.ts 文件)。
因此,在来自app.component.ts 文件的userPage 方法中,现在我们在发布事件之前使用共享服务保存用户ID:
import { Events } from 'ionic-angular';
constructor(public events: Events, public paramService: ParamService) {}
userPage(user_id) {
this.paramService.selectedUser = user_id;
this.events.publish('user:selected');
}
删除UserPage标签的代码,并将其添加到TabsPage:
import { ViewChild, ... } from '@angular/core';
import { Events, NavController, ... } from 'ionic-angular';
@ViewChild('tabs') tabRef: Tabs;
constructor(public events: Events, public navCtrl: NavController) {
this.events.subscribe('user:selected', () => {
// First select the proper tab if any other tab was selected
this.tabRef.select(5);
});
}
最后但同样重要的是,在UserPage 选项卡中,使用ionViewWillEnter 生命周期挂钩从paramService 中获取选定的user_id:
public userToShow: any;
constructor(public paramService: ParamService) {}
ionViewWillEnter() {
this.userToShow = this.paramService.selectedUser;
}