0
votes

I have an angular application in which, there is a service having 3 types of variables: simple boolean, behaviorSubject of type boolean and an Object with the property of type number.

I am updating all the 3 variables from a child component using the service's getter-setter methods. Now I want those updated changes of service variables in my parent component without emitting change from child component. It is working fine for the object and behaviorSubject, but it is not reflecting that change in the simple boolean variable.

So, what is the difference among these 3, that can lead to this behaviour?

I have created a simple stackblitz demo to demonstrate the above. here's the link: Stackblitz

2

2 Answers

3
votes

To break the issue down more simply :

let myBoolean = false;
let newBoolean = myBoolean;
newBoolean = true;
console.log(newBoolean); //true
console.log(myBoolean); //false

Whereas

let myBoolean = { data : false };
let newBoolean = myBoolean;
newBoolean.data = true;
console.log(newBoolean); //true
console.log(myBoolean); //true

When assigning primitive values, you are assigning by value. Changing this value doesn't affect the original. When you are doing the same with objects, you are still passing by value (The pointer to the original object), but changing a property on that object will change the original object too. Javascript is a bit weird like that, here's a better explanation on Stackoverflow : https://stackoverflow.com/a/6605700/177516

Now in your example, the reason the boolean doesn't work is because you are assigning it in your appComponent, therefore cloning the value and any changes to the original won't affect it. It's not an Angular problem, but a javascript one.

If for example you made a change inside your view to do something like

{{service.isValue}}

Then this would update in realtime because you are pointing to the original reference, not your cloned version.

0
votes

Your issue is the ngOnInit subscribe is misformatted. It looks like your intention is to change the three values.

Change your existing:

 ngOnInit() {
  this.service.isObservableValue
  // .pipe(take(1))
  .subscribe(bool => (this.isObservaleValue = bool)); // <-- only this gets called on subscribed event

 this.isValue = this.service.isValue; // <--- these two lines only get called once
 this.data = this.service.response.data; // <--- this too
}

To this:

 ngOnInit() {
  this.service.isObservableValue
  // .pipe(take(1))
  .subscribe(bool => { // <-- add a bracket here
    this.isObservaleValue = bool;
    this.isValue = this.service.isValue;
    this.data = this.service.response.data;
  } // <-- and another one here.
  );
 }