Ionic 4- Receive variable update with Behaviorsubject

Asked

Viewed 79 times

0

In the home I have a list of products that click opens the product modal with a button to add to cart. When you add the quantity appears next to the icon. I want to close this modal on app. be updated the icone that is in the footer. I need to update this cart with the value of the modal that was closed without refresh.

service.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();
  }

modalProduct.ts

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

app.componentts.

 quantshop;
 subscription: Subscription;

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

app module.

  providers: [servico]

image

inserir a descrição da imagem aqui

  • I don’t understand why you used this.subscription = this.global.getTotalShop().subscribe(... and not this.servico.getTotalShop().subscribe(... ??

  • Typing error, corrected by.

  • Alessandro did not understand very well! It would not be enough to perform a function when closing the modal that emits a value in your BehaviorSubject since the app.component is "listening" to this observable?

  • I don’t understand why use the variable Subscription, pq the value returned (val) is already being passed to another variable this.quantshop = val.

  • @Marcelovismari the app.Component doesn’t seem to hear

  • @Leandrade was an attempt, but it also did not work.

  • The code is asyncrono the value will only be updated within the subscribe which is the code that will run every time the value changes.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.