Reputation: 93
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
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
Reputation: 31105
BehaviorSubject
.Controller
const personSrc = new BehaviorSubject<any>({
firstname:"Tom",
lastname:"Hanks"
};
const person$ = this.personSrc.asObservable();
async
pipe.Template
<ng-container *ngIf="(person$ | async) as person">
<span *ngIf="person['firstname'] !== 'Bill'">
{{ person.lastname }}
Some properties
<span>
</ng-container>
Controller
this.personSrc.next({firstname: "Bill", lastname: "Watterson"})
Upvotes: 0
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