我想将值存储在任何组件可以观看和更改的服务中,并且当任何组件更改值时,所有其他观察值的组件都将更新。通过服务中的可观察角度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')
}
}