我正在使用兩個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文件中? 什麼是最佳實踐?