I would like to store a value in a service which any component can watch and change, and when any component changes the value, all other components watching the value will be updated.
After some research, i have found this solution that makes sense to me but does not work.
https://plnkr.co/edit/mlVfASdAw1vbpJRhGFov?p=preview
Service
export class Service {
value: string;
subject: Subject<string> = new Subject<string>();
setValue(value: string): void {
this.subject.next(value);
}
getObservable(): Observable<string> {
return this.subject.asObservable();
}
}
Component 1
@Component({
selector: 'comp-1',
template: `
<div>
Value in component 1: {{value}}
</div>
<button (click)="update()">set value to '1'</button>
`,
providers: [Service]
})
export class Component1 {
subscription;
value: string;
constructor(private service: Service) {
this.headerStateSubscription = this.service.getObservable().subscribe(value => {
this.value = value;
});
}
update() {
this.service.setValue('1')
}
}
Component 2
@Component({
selector: 'comp-2',
template: `
<div>
Value in component 2: {{value}}
</div>
<button (click)="update()">set value to '2'</button>
`,
providers: [Service]
})
export class Component2 {
subscription;
value: string;
constructor(private service: Service) {
this.headerStateSubscription = this.service.getObservable().subscribe(value => {
this.value = value;
});
}
update() {
this.service.setValue('2')
}
}