robb
robb

Reputation: 93

Observe changes in an object property with Angular

In my Angular2 application I have an object with some properties similar to this:

var person = { 
   firstname:"Tom", 
   lastname:"Hanks" 
};

If one of these properties, for example "firstname" changes to "Bill", I would like to hide some elements in the HTML page. Is there any way to observe the changes of this object? What is the best way to do this using RxJS? I am a novice to Angular and RxJS.

Upvotes: 3

Views: 3528

Answers (3)

shutsman
shutsman

Reputation: 2510

you can Observe object property by distinctUntilKeyChanged

distinctUntilKeyChanged - Only emit when the specified key value has changed

Example:

console.clear();
import { BehaviorSubject } from "rxjs";
import { distinctUntilKeyChanged } from "rxjs/operators";

const personSrc = new BehaviorSubject<any>({
  firstname: "Tom",
  lastname: "Hanks"
});

setTimeout(() => {
  const newPerson = { firstname: "Bill", lastname: "Smith" };
  personSrc.next(newPerson);
}, 5000);

personSrc.pipe(distinctUntilKeyChanged("firstname")).subscribe(console.log);

When the value of firstname is changed it will emit a new value

DEMO: https://stackblitz.com/edit/rxjs-distinct-example-a7t4jk?file=index.ts

Upvotes: 2

Barremian
Barremian

Reputation: 31105

  1. Wrap the object in a multicast observable like BehaviorSubject.

Controller

const personSrc = new BehaviorSubject<any>({ 
  firstname:"Tom", 
  lastname:"Hanks" 
};

const person$ = this.personSrc.asObservable();
  1. Display it in the template using the async pipe.

Template

<ng-container *ngIf="(person$ | async) as person">
  <span *ngIf="person['firstname'] !== 'Bill'">
    {{ person.lastname }}
    Some properties
  <span>
</ng-container>
  1. Push any changes to the object through the observable.

Controller

this.personSrc.next({firstname: "Bill", lastname: "Watterson"})

Upvotes: 0

AlleXyS
AlleXyS

Reputation: 2598

You can use subjects.

export class YourService {
  person$: Subject<Person> = new Subject<Person>();

  setPerson(person) {
    this.person$.emit(person);
  };
}

your component:

constructor(
  private yourService: YourService
) {}

ngOnInit() {
 
  this.yourService.person$.subscribe(person => {
    // here you get the new data
 });
}

changePersonName() {
   this.person.firstName = 'Bill';
   this.yourService.setPerson(this.person); // this will fire the person$ Subject
}

Upvotes: 1

Related Questions