To get your value pushed out of the Subject
, so create an Observable
from it and subscribe
.
If you want a local version of the value, you need to take a copy due to objects being passed by reference in JavaScript, so create a new object when you subscribe.
You can do this with Spread Syntax.
Then you can assign whatever values you like to the local object without effecting the Subject
.
e.g. (StackBlitz)
const theRuleSbj = new BehaviorSubject<Rule>(null);
const theRule$ = theRuleSbj.asObservable();
// The observable will emit null on the initial subscription
// Subject might be a better fit
theRule$.subscribe(rule => {
console.log(`Subscription value:`, rule);
// Use object spread to create a new object for your component
this.rule = { ...rule };
});
// Update the Subject, it will console log new value
// and update your local value
theRuleSbj.next({ name: 'Name 1'});
// Update your local value, does not effect your Subject value
this.rule.name = 'Name 2';
// Confirm that they are differant
console.log(`Subject Value:`, theRuleSbj.getValue());
console.log(`Local Value`, this.rule);
// Be careful as when you update the Subject, your local value will be updated
theRuleSbj.next({ name: 'Name 3'});
console.log(`Subject Value (after subject update):`, theRuleSbj.getValue());
console.log(`Local Value (after subject update)`, this.rule);
Be warned, having subscribed you will get all updates to the subject value pushed to your local value, you may or may not want this to happen.
If you only want the one value in the component, you can pipe()
the observable
and use take(1)
to get one value out, but as you initialise the Subject
as BehaviourSubject
, you will only get the null
value. You may want to change this to a Subject
so when the first value is pushed to the Subject
your component receives it.
const theRuleSbj = new Subject<Rule>();
/* other code omitted */
theRule$
.pipe(take(1))
.subscribe(rule => {
console.log(`Subscription value:`, rule);
this.rule = { ...rule };
});