在我的BehaviorSubject
地址元素中有2个属性。在这个如何单独更新单个属性?
这是我的尝试:
myAddress:any = {
"plot":32,
"street":"D15 Road"
}
private address = new BehaviorSubject(this.myAddress);
addressClass = this.address.asObservable();
updateAddress(newAddress){
this.address.next(newAddress);
}
我想像这样更新:
import { Component, Input, OnInit } from '@angular/core';
import { SharedObject } from './shared.object';
@Component({
selector: 'hello',
template: `
<h1>Hello {{name}}!</h1>
<h2>City Name in Hero : {{heroName}}</h2>
<h3>{{plotNo}}</h3>
<button (click)="updatePlot(44)">Update Ploat </button>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
plotNo:number;
address:any;
constructor(private shared:SharedObject){
}
ngOnInit(){
this.shared.addressClass.subscribe((address) => {
this.plotNo = address.plot;
})
}
updatePlot(newNo){
this.shared.updateAddress(newNo); //don't know how to update plot no alone?
}
}
答案 0 :(得分:3)
您可以使用spread运算符和BehaviorSubjects值,如下所示:
updateAddress(newAddress){
this.address.next({...this.address.value, ...newAddress});
}