I want to keep total amount of my component updated as it's changing, and I'm wondering is this right:
I have a shared.service.ts
which is injected into my component so it looks like this (my shared service):
shared.service.ts
private sumEmit= new BehaviorSubject<number>(0);
public updateValues() {
this.sum= 0;
this.sum+= +(price*quant).toFixed(2);
this.sumEmit.next(this.sum);
}
Method to get total amount also in service:
getTotal(): BehaviorSubject<number> {
return this.sumEmit;
}
So, every time updateValues()
method is called, it will emit value of sum, that's right?
And in my component which need to retreive value everytime value is changed I did this:
mycomponent.component.ts
First of all I injected shared service, after that in ngOnInit
life cycle hool I wrote:
// simple variable to hold value from service
total : number;
ngOnInit()
{
this.total = this.SharedService.getTotal();
}
Does this mean that my value will be up to date everytime total amount is changed?
Most confusing part for me is that I called this method only once in a ngOnInit
which is rendered when component is opened, but value is kept updated.. Could anyone explain me this please? How come variable in my component is aware when value is changed in service? Which part is responsible for that?
Thanks