Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular BehaviorSubject subscription fires only once

I have an Angular service with a boolean property called must_checkout. My service also contains a property called observable_must_checkout which is a BehaviorSubject looking into must_checkout.

Then, In my component I subcribe to observable_must_checkout.

This works and the component receives the event the first time must_checkout changes. However this only fires once, and subsequent changes to must_checkout are not working:

Service:

import { Injectable,  Input, Output } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

export class OrderingService
{

  must_checkout: boolean;
  observable_must_checkout = new BehaviorSubject<boolean>(this.must_checkout);

  constructor([...])
  {
    this.observable_must_checkout = new BehaviorSubject<boolean>(this.must_checkout);
  }

  ChangeSomething()
  {
    console.log("changing the value here...");
    this.must_checkout = true;
  }


}

Parent component:

import { Component, OnInit } from '@angular/core';
import { OrderingService } from 'src/app/services/ordering.service';

@Component({
  selector: 'app-settle',
  templateUrl: './settle.component.html',
  styleUrls: ['./settle.component.css']
})

export class SettleComponent implements OnInit
{
  constructor(private OrderingService: OrderingService) { }

  ngOnInit()
  {
        this.basket = new OrderingService();
        this.basket.observable_must_checkout.subscribe((newValue: boolean) => { alert("value changed: " + newValue)  });

  }

  ngOnDestroy() {
    this.basket.observable_must_checkout.unsubscribe();
  }

}
like image 757
Yann Avatar asked Sep 06 '25 03:09

Yann


1 Answers

I'm not seeing a call to next(), which is how you fire new events to the current subscribers of your BehaviorSubject. You are looking for something like this.

  ChangeSomething()
  {
    console.log("changing the value here...");
    this.observable_must_checkout.next(true); 
  }

https://www.learnrxjs.io/subjects/

Also, you don't need to intialize the subject in the constructor since you do it a few lines above:

  observable_must_checkout = new BehaviorSubject<boolean>(this.must_checkout);

  constructor([...])
  {}
like image 183
Damian C Avatar answered Sep 07 '25 23:09

Damian C