首页 > 解决方案 > Ionic 4-使用 BehaviorSubject 接收变量更新

问题描述

在家里,我有一个产品列表,点击后会打开产品模式,并带有一个添加到购物车的按钮。当您添加金额时,图标旁边会出现。我想在 app.component 中关闭此模式以更新页脚中的图标。我需要使用在未刷新的情况下关闭的模式值更新此购物车。

服务商.ts

public totalShop: BehaviorSubject<String>;

 constructor() {
    this.totalShop = new BehaviorSubject('0');       
 }

 setTotalShop(val) {    
    this.totalShop.next(val);    
  }

  clearTotalShop() {
    this.totalShop.next('0');
  }

  getTotalShop(){    
    return this.totalShop.asObservable();
  }

modalProducts.ts

fnShop(){
    quantidade = quantidade +1
    this.servico.setTotalShop(quantidade)
 }

app.component.ts

quantshop;
 subscription: Subscription;

 ngOnInit(): void {
   this.subscription = this.servico.getTotalShop().subscribe(val => this.quantshop = val);
   console.log(this.quantshop)
}

应用程序模块

  providers: [servico]

图像

在此处输入图像描述

标签: angularionic4

解决方案


我想你使用有角度的材料徽章。

您可以在 html 中使用角度异步管道。

<mat-icon [matBadge]="global.getTotalShop() | async">icon</mat-icon>

您需要将服务公开以在 html 中访问它或在您分配 BehaviourSubject 的 component.ts 中创建另一个变量。


推荐阅读