I want to share a state (just a string) with multiple components. To do so I came across this site and implemented it to my app like this:
my.component.ts
// ...
onButtonClick(event: MouseEvent) {
console.log('1');
this.myService.getStatus().subscribe(
(currentStatus) => {
console.log('2');
if (currentStatus=== 'success') {
// foo
} else {
// bar
}
},
(error) => { /* ... */ },
() => { /* ... */ }
);
console.log('3');
}
// ...
Note: I added the console.logs to debug.
This is my service
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MyService {
private status = new Subject<string>();
constructor() { }
getStatus(): Observable<string> {
return this.status .asObservable();
}
updateStatus(updatedStatus: string) {
this.status.next(updatedStatus);
}
}
My problem is now, that I don't understand, why subscribe() gets fired after I update the status with another button, so the call stack is something like *Button Click* -> '1' -> '3' -> *btnUpdate click* -> '2'
. I do call updateStatus() earlier to set a value.
I used observables elsewhere in the same project but they behave as expected, what is different to this one?
Edit
This is for future readers: Refer the answer of Yevhenii Dovhaniuk, he gave me a better undestanding of Observables and his answer worked as well