I am bit confused on the way BehaviourSubject is executed and looking for help. I have one component - my-component.ts and service file - my-service.ts. ButtonClicked() method is called from another component on click on button.
my-service.ts
myEventEmitter = new BehaviorSubject<string>('DEFAULT');
ButtonClicked() {
debugger;
this.myEventEmitter.next("1st Value");
debugger;
this.myEventEmitter.next("2nd value");
}
my-component.ts
ngOnInit() {
this.myServiceService.myEventEmitter.subscribe((value) => {
debugger;
console.log('Value 1 is ' + value);
});
this.myServiceService.myEventEmitter.subscribe((value) => {
console.log('Value 2 is ' + value);
});
}
Output of the above on console will be:
Value 1 is 1st Value
my-component.component.ts:21 Value 2 is 1st Value
my-component.component.ts:18 Value 1 is 2nd value
my-component.component.ts:21 Value 2 is 2nd value
BUT, IF I MOVE THE CODE FROM COMPONENT TO SERVICE FILE, I WILL GET DIFFERENT OUTPUT.
<pre>my-service.ts
myEventEmitter = new BehaviorSubject<string>('DEFAULT');
ButtonClicked() {
this.myEventEmitter.next("1st Value");
this.myEventEmitter.next("2nd value");
this.myEventEmitter.subscribe((value) => {
console.log('1:' + value);
});
this.myEventEmitter.subscribe((value) => {
console.log('2:' + value);
});
}
Output of the above on console will be:
my-service.service.ts:21 1:2nd value
my-service.service.ts:31 2:2nd value
What is the different between placing subscriber in component file vs in service file?
I am using Angular 17.3.9.
What I have tried:
I tried searching on youtube but got only videos on related to first approach.