Update tabs badge total from a different component

I will try to be as simple as possible, example:

tabs.html

...
<ion-tab tabIcon="cart" tabTitle="Cart" [tabBadge]="count$ | async" tabBadgeStyle="danger" [root]="tab3"></ion-tab>
...

tabs.ts

...
count$: Observable<number>;
...
constructor(public navCtrl: NavController,  
     public shoppingService: ShoppingService) {
...
ngOnInit(){  
    this.count$ = this.shoppingService.listSize;
  }

tab3-page.html

...
<button ion-button item-end (click)="addToCart(p)">
...

tab3-page.ts

...
constructor(public navCtrl: NavController, 
    private shoppingService: ShoppingService ){
...

private addToCart(product: ProductInterface){
    this.shoppingService.addItem(product);
}
...

shopping.service.ts

...
  private listSizeSubject: Subject<number>;
  private _listSize: Observable<number>;
...
  constructor(){
...
    this.listSizeSubject = new Subject();
    this._listSize = this.listSizeSubject.asObservable();
  }

  get listSize(){
    return this._listSize;
  }

  public addItem(product: ProductInterface){
    this.products.push(product);
    this.listSizeSubject.next(this.products.length);//next method updates the stream value
  }
...

Basically you use a Service to be used by the different tabs, so you keep your Observable there, and we need to update the sequence stream so we use a Subject object which is an Observable and an Observer.

Note that we are using async pipe so it subscribes to the observable that we passed, the pipe that gets the value out of it.

Hope that helps everyone, it took me awhile, and most of people are using localStorage or Events.

2 Likes