【问题标题】:How to update `BehaviorSubject` single value alone如何单独更新“BehaviorSubject”单个值
【发布时间】:2018-05-17 14:22:55
【问题描述】:

在我的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?
  }

}

【问题讨论】:

    标签: angular angular5


    【解决方案1】:

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

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

    Here is a stackblitz demo.

    【讨论】:

    • 我同意。如果这是 2 个值,我们可以以任何方式进行管理。如果对象具有超过 50 个值...如何处理?
    • 没关系,扩展运算符只会替换对象newAddress中的值,并保持地址的初始值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    • 2021-08-11
    相关资源
    最近更新 更多