Reputation: 1686
I want components to be able to subscribe or be notified of a change on a variable in a service.
I looked into Observables but I don't think this would work because you need to complete the stream and I need to know about changes the variable over the entire time the component is active.
Does anyone know a good strategy for this?
Upvotes: 3
Views: 2588
Reputation: 16718
Have you tried Subject
or any of its variations?
Example using BehaviorSubject
Service:
export class MyService {
myVariableSubject = new BehaviorSubject<number>(0);
increase() {
this.myVariableSubject.next(this.myVariableSubject.value + 1);
}
}
Component:
constructor(private myService: MyService) {}
ngOnInit() {
this.myService.myVariableSubject.subscribe((value: number) => console.log(value));
}
Warning: This might not be the most suitable solution to your problem (which you never state).
Upvotes: 10