Martheli
Martheli

Reputation: 981

Update variable tied to Behavior Subject without updating the Behavior Subject

I have a behavior subject that takes a User object defined like this:

userObservable = new BehaviorSubject<User>(null);

I then have a function that gets the current value of it, makes some changes to local variable and POST the changes but I don't want to change the value of the Behavior Subject:

const newUser = this.userDetailsObservable.getValue()
newUser.fName = 'John'

this.sendData(newUser)

In doing this, the Behavior Subject changes without me calling .next(). How do I make local changes to a variable of a behavior subject without actually changing the behavior subject?

Upvotes: 1

Views: 577

Answers (1)

Reza
Reza

Reputation: 19913

getValue() doesn't change the value of behavior subject. it could have been changed in sendData. You can create a new instance of your object to not have any reference and check if it is still changing

you can use spread

const newUser = {...this.userDetailsObservable.getValue()}

or you can use old classic way as

const newUser = JSON.parse(JSON.stringify(this.userDetailsObservable.getValue()));

Upvotes: 1

Related Questions