如何更改Observable对象的属性.Angular 2/BehaviorSubject

ilo*_*aAJ 8 rxjs angular

我有一个Person类型的对象,其中包含firstName,lastName,age字段.我使用行为主题检测到任何变化.我有一个观察组件,订阅了此Person对象的每个更改.一旦更改检测到观察组件将调用方法.我希望此方法更改Observable Person Object的属性.

在我的服务中

export class PersonService {

    personToCopySource = new BehaviorSubject<Person>(null);
    personToCopy = this.personToCopySource.asObservable();
Run Code Online (Sandbox Code Playgroud)

在我的组件中

 export class ObservingComponent {

    constructor(public person: Person) {}

    ngOnInit(){
      this.personService.person.subscribe(
         data=> {
           this.updateMethod()
          }
      )
    }

   updateMethod(){
     this.personService.firstName = 'updated First Name';
   }
Run Code Online (Sandbox Code Playgroud)

当我更改Observing对象的属性时,我收到此错误.Observable类型中不存在"Property"firstName

小智 2

可观察者是一个流。它没有属性。你想让我做什么?你想把你自己的价值放到流上并进行firstName更新吗?在这种情况下,你可以尝试一下Subject#next

export class PersonService {

  personToCopySource = new BehaviorSubject<Person>(null);
  personToCopy = this.personToCopySource.asObservable();

  // Provide a method to update a person,
  // by putting a new or updated person on the stream.
  update(person: Person) { 
    this.personToCopySource.next(person); 
  }
Run Code Online (Sandbox Code Playgroud)

在我的组件中

export class ObservingComponent {

    constructor(public person: Person) {}

    ngOnInit(){
        this.personService.personToCopy.subscribe(
            data=> {
                this.updateMethod(data)
            })
    }

    updateMethod(data){
        this.personService.update({...data, firstName: 'updated First Name'});
    }
Run Code Online (Sandbox Code Playgroud)