angular - 如何減輕標籤點擊的影響?
我有一個分頁群組:
<ion-tabs>
<ion-tab [root]="tab1Root" tabTitle="Programmes" tabIcon="icon-programmes"></ion-tab>
<ion-tab [root]="tab2Root" (ionSelect)="studioCheck()" tabTitle="Studio" tabIcon="icon-studio"></ion-tab>
<ion-tab [root]="tab3Root" tabTitle="Library" tabIcon="icon-library"></ion-tab>
<ion-tab [root]="tab4Root" tabTitle="Profile" tabIcon="icon-profile"></ion-tab>
</ion-tabs>
當使用者點擊第二個標籤('Studio')時,我需要檢查他們是否已經有權限訪問它。如果有,太好了;如果沒有,我想顯示一個吐司通知並加載第一個標籤。
我該怎麼做這個?
我以為在 studioCheck() 上使用 return false 就足夠了,但事實並非如此。
Typescript :
studioCheck() {
console.log('Studio visited');
// Grab studio selected level
this.storage.get('studio_level').then((val) => {
console.log('Storage queried');
if(val) {
console.log('Level ID: ', val);
return true;
} else {
// No level selected
let toast = this.toastCtrl.create({
message: 'Please choose a programme in order to use the Studio',
duration: 3000,
position: 'top'
});
toast.present();
this.navCtrl.parent.select(0);
return false;
}
});
}
我以為也許 ionSelect 不會等待非同步的 storage.get 呼叫,所以我就在函式的最上方做了 return false;,但結果也是一樣。
有什麼想法嗎?
答案#1
像這樣調整視圖
<ion-tabs #tabs>
<ion-tab [root]="tab1Root" tabTitle="Programmes" tabIcon="icon-programmes"></ion-tab>
<ion-tab [root]="tab2Root" (ionSelect)="studioCheck()" tabTitle="Studio" tabIcon="icon-studio"></ion-tab>
<ion-tab [root]="tab3Root" tabTitle="Library" tabIcon="icon-library"></ion-tab>
<ion-tab [root]="tab4Root" tabTitle="Profile" tabIcon="icon-profile"></ion-tab>
</ion-tabs>
然後在控制器中:
export class MyPage {
@ViewChild("tabs") public tabs: Tabs;
...
studioCheck() {
console.log('Studio visited');
// Grab studio selected level
this.storage.get('studio_level').then((val) => {
console.log('Storage queried');
if(val) {
console.log('Level ID: ', val);
return true;
} else {
// No level selected
let toast = this.toastCtrl.create({
message: 'Please choose a programme in order to use the Studio',
duration: 3000,
position: 'top'
});
toast.present();
this.tabs.select(0);
}
});
}
}
解釋
- 為了在程式碼中切換標籤,你必須取得
Tabs的實例並在其上呼叫select。 - 請記住,當標籤被選中時會觸發
ionSelect,因此返回值會被忽略。 - 由於
this.storage.get,你的程式是非同步的,所以return false;無法離開studioCheck方法
