在 Ionic 2 上动态更新标签徽章

Updating tab badge dynamically on Ionic 2

我希望在单击按钮时动态更新徽章值。

tabs.html

...
        <ion-tab [root]="tab1Root" tabTitle="Product" tabIcon="search"></ion-tab>
        <ion-tab [root]="tab2Root" tabTitle="Cart" tabIcon="cart" tabBadge="{{cartCount}}" tabBadgeStyle="danger"></ion-tab>
...

tabs.ts

export class TabsPage {
...
    cartCount = 0;

    tab1Root = ProductPage;
    tab2Root = CartPage;
...
}

product.html

<button ion-button full (click)="updateCart('add', p.id)">Buy Now</button>

product.ts

export class ProductPage {
...
    updateCart(action, id) {
        let cartCount = 1;

        let alert = this.alertCtrl.create({
            title: 'Success!',
            subTitle: 'You have added 1 product to the cart.',
            buttons: ['OK']
        });

        alert.present();
    }
...
}

正如我所想,let cartCount = 1; 什么都不做。我已经搜索了一个解决方案,但大多数都是针对 Ionic 1 或 AngularJS,这对我一点帮助都没有。

您可以使用 Ionic events for that. Please take a look at this working plunker。正如您在那里看到的那样,在第一个选项卡中,我们会在徽章需要更新时发布一个事件:

import { Component } from '@angular/core';
import { Events } from 'ionic-angular';

@Component({..})
export class FirstTabPage {

  private count: number = 0;

  constructor(public events: Events) {}

  public updateTabBadge(): void {
    this.events.publish('cart:updated', ++this.count);
  }

}

然后我们在包含两个选项卡的页面中订阅该事件:

import { Component } from '@angular/core';
import { Events } from 'ionic-angular';

@Component({...})
export class FirstTabPage {

  private count: number = 0;

  constructor(public events: Events) {}

  public updateTabBadge(): void {
    this.events.publish('cart:updated', ++this.count);
  }

}

并且在视图中:

<ion-header>
  <ion-navbar>
    <ion-title>Tabs</ion-title>
  </ion-navbar>
</ion-header>
<ion-tabs #myTabs>
  <ion-tab [root]="tab1Root" tabTitle="First Tab"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Second Tab" [tabBadge]="cartCount"></ion-tab>
</ion-tabs>

另请注意,应使用 属性 绑定 而不是 字符串插值 来绑定 tabBadge 属性: [tabBadge]="cartCount"


更新

就像@skinny_jones mentioned in the comments, you could also use Subjects/Observables to achieve the same result. You can find more information in this blog post