gpt4 book ai didi

angular - 如何单独更新 `BehaviorSubject`单值

转载 作者:太空狗 更新时间:2023-10-29 18:07:51 26 4
gpt4 key购买 nike

在我的 BehaviorSubject 中,address 元素有 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?
}

}

最佳答案

您可以像这样使用扩展运算符和 BehaviorSubjects 值:

updateAddress(newAddress){
this.address.next({...this.address.value, ...newAddress});
}

Here is a stackblitz demo.

关于angular - 如何单独更新 `BehaviorSubject`单值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50393901/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com