How to Change the property of an Observable Object. Angular 2/BehaviorSubject

Viewed 7682

I have an object of type Person which has fields of firstName, lastName, age. I detect for any change using Behavior Subject. I have an observing component that is subscribed to every change on this Person Object. Once the change detects the observing component will call a method. I want this method to change the property of the Observable Person Object.

In My Service

export class PersonService {

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

In My Component

 export class ObservingComponent {

    constructor(public person: Person) {}

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

   updateMethod(){
     this.personService.firstName = 'updated First Name';
   }

When I change the property of the Observing object I'm getting this error. "Property" firstName does not exist on type Observable

1 Answers

An observable is a stream. It does not have properties. What do you want to do? Do you want to put your own value on the stream, with firstName updated? In that case, you could try 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); 
  }

In My Component

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'});
    }
Related