网站搜索

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 方法退出