Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update the value of an RxJS Observable created using of(myArray)

I came into a problem while working with Angular and Observable.

I got a Basket page subscribing to an Observable of an array in a BasketService, containing my customers orders. When i click on the validate button, i empty my ordersArray but even though my Basket page has subscribed to my observable, it does not update.

In my BasketPage.ts

  ngOnInit() {
this.nourritureSubscription = this.panierService.nourritureStore.subscribe((data) => {
  if(data.length === 0) {
    this.isNourriturePanierEmpty = true;
  } else {
    this.nourriturePanier = data;
    console.log(data)
    this.isNourriturePanierEmpty = false;
  }
});
this.menuSubscription = this.panierService.menuStore.subscribe((data) => {
  if(data.length === 0) {
    this.isMenuPanierEmpty = true;
  } else {
  this.menuPanier = data
  console.log(data)
  this.isMenuPanierEmpty = false;
  }
})
}
consumePanier(){
let commandeSucess : boolean;
this.panierService.consumePanier()
this.commandeEnvoyee();
}
async commandeEnvoyee() {
const alert = await this.alertCtrl.create({
    header: 'Commande envoyée !',
    message: 'Votre commande a été approuvée et enregistrée',
    buttons: [
        {
            text: 'Valider',
            role: 'cancel',
            cssClass: 'primary',
            handler: () => {
              this.ngOnInit();
             }
         }
      ]
 });

 await alert.present();
}

In my BasketService.ts

nourritureArray: Nourriture[] = [];
menuArray: Menu[] = [];

nourritureStore = of(this.nourritureArray)
menuStore = of(this.menuArray)

consumePanier(){
let panierRef = [];
let user=JSON.parse(localStorage.getItem('user'));

panierRef.push({idUser: user.id})

Object.entries(this.nourritureArray).forEach(([key, value])=>{
  panierRef.push({idNourriture: value.id, nameNourriture: value.name})
})
Object.entries(this.menuArray).forEach(([key, value])=>{
  panierRef.push({idMenu: value.id, nameMenu: value.name})
})

let commande = JSON.parse(JSON.stringify(panierRef));

panierRef= [];

this.nourritureArray = [];
this.menuArray = [];
}

Any though ?

Hints : -When I reload the url, i have the updated store (but i can't force reload with router don't know why...) -When i refresh with ngOnInit i get the old value from observable, even though my array is empty...

like image 846
Julien FEGER Avatar asked Jan 19 '26 13:01

Julien FEGER


1 Answers

The of method simply creates an Observable that will emit the given arguments and then complete. It will not track any changes you make to the arguments after the fact.
You might want take a look at using a Subject. A subject acts as both an Observer and an Observable, allowing you to push data to the subjects subscribers. In your case, this data would be your store arrays. Instead of creating the Observables from the literal value, create them from a subject that you can update when the value changes.
Here's a super simplified example for a single array that accomplishes what I think you are looking for:

export class BasketService {

  // Create a new BehaviorSubject with an initial value of []
  private Subject<Menu[]> menuSubject = new BehaviorSubject<>([]);

  // Expose the menuSubject as an Observable (prevents consumers from pushing values)
  Observable<Menu[]> menuStore = menuSubject.asObservable();

  public addMenuItem(menuItem: Menu) {
    // Get the current value of the menu store
    const menus = this.menuSubject.getValue();
    // Add the new menu 
    menus.push(menuItem);
    // Push the updated menu to the subject
    this.menuSubject.next(menus); // This is what notifies subscribers
  }

  public consumePanier() {

    /// ... your business logic

    // Update the value of the subject with an empty array
    this.menuSubject.next([]); // This is what notifies subscribers
  }  
} 

The important thing to note in this example is that any time you make a change to the data, you must push the new data to the subject with the next method in order for the subscribers to be notified.

like image 107
Jonathan Seed Avatar answered Jan 22 '26 05:01

Jonathan Seed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!