我正在使用两个TabItems的Nativescript(Angular 2)TabView。 XML分为三个文件。一个持有TabView和两个其他TabItem。因此我也有三个TypeScript组件。当tabitem被选中时触发NativeScriptcript tabitem事件
此刻我在第二个TabItem的onInit方法中加载数据。问题是当TabView的第一个TabItem被显示/加载时,这个操作已经发生。 仅当选择第二个TabItem时才加载此数据的最佳做法是什么?
这是我的(缩短)代码:
home.page.html:
<ActionBar title="Home"></ActionBar>
<TabView #tabview (selectedIndexChanged)="tabIndexChanged($event)" toggleNavButton>
<StackLayout *tabItem="{title: 'Tab 1'}">
<tab1></tab1>
</StackLayout>
<StackLayout *tabItem="{title: 'Tab 2'}">
<tab2></tab2>
</StackLayout>
</TabView>
home.page.ts:
import {Component} from "@angular/core";
@Component({
selector: "home-page",
templateUrl: "./pages/home/home.page.html",
providers: []
})
export class HomePage {
public activeTab: string;
public constructor() {
}
public tabIndexChanged(e: any) {
switch (e.newIndex) {
case 0:
console.log(`Selected tab index: ${e.newIndex}`);
break;
case 1:
console.log(`Selected tab index: ${e.newIndex}`);
break;
default:
break;
}
}
}
tab1.tab.html:
<StackLayout orientation="vertical" class="p-20">
<Label text="Tab 1"></Label>
</StackLayout>
tab1.tab.ts:
import { Component, OnInit } from "@angular/core";
@Component({
selector: "tab1",
templateUrl: "./pages/partials/tab1.tab.html",
providers: []
})
export class Tab1 implements OnInit {
public constructor() {}
public ngOnInit() {
console.log("init Tab 1");
}
}
tab2.tab.html:
<StackLayout orientation="vertical" class="p-20">
<Label text="Tab 2"></Label>
</StackLayout>
tab2.tab.ts:
import { Component, OnInit } from "@angular/core";
@Component({
selector: "tab2",
templateUrl: "./pages/partials/tab2.tab.html",
providers: []
})
export class Tab2 implements OnInit {
public constructor() {}
public ngOnInit() {
console.log("init Tab 2");
this.getSomeDataViaHttp();
}
private getSomeDataViaHttp() {
//getting data from an API
}
}
是否有角2/Nativescript比其他OnInit的事件,这将有助于在这里? 或者我应该在home.page.ts中使用tabIndexChanged方法吗? 或者把TabView的所有逻辑和XML都放回到一个xml文件和一个ts文件中? 什么是最佳实践?