3

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.

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

0
  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"})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.