我想將值存儲在任何組件可以觀看和更改的服務中,並且當任何組件更改值時,所有其他觀察值的組件都將更新。通過服務中的可觀察角度2組件間的角度2雙向綁定
經過一番研究,我發現這個解決方案對我來說很合理,但不起作用。
https://plnkr.co/edit/mlVfASdAw1vbpJRhGFov?p=preview
服務
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();
}
}
組件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')
}
}
組件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')
}
}