代码之家  ›  专栏  ›  技术社区  ›  3gwebtrain

如何单独更新'BehaviorSubject'单个值

  •  3
  • 3gwebtrain  · 技术社区  · 6 年前

    在我的 BehaviorSubject 具有2属性的address元素。在这种情况下,如何单独更新单个属性?

    以下是我的尝试:

    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?
      }
    
    }
    
    1 回复  |  直到 6 年前
        1
  •  15
  •   ibenjelloun    6 年前

    可以使用spread运算符和BehaviorSubjects值,如下所示:

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

    Here is a stackblitz demo.