Reputation: 14596
In my angular application, I have the following array of objects:
public data = [
{a: 0, b: [{q: 1, z: 2}]}
{a: 1, b: [{q: 4, z: 9}]}
]
Question: How can I subscribe to any changes in the array (also including changes in nested objects)?
Expected result: A function that fires every time data
is changed
Upvotes: 1
Views: 2909
Reputation: 18123
First you need a service to wrap your state (here you can also use more sophisticated frameworks like Redux but lets keep it simply for the start), this is usually a good idea to decouple your application
import {BehaviorSubject, Observable} from "rxjs/index";
import {Injectable} from "@angular/core";
@Injectable({
providedIn: 'root',
})
export class StateService {
private readonly subject: BehaviorSubject<any> = new BehaviorSubject({});
public readonly observable: Observable<any> = this.subject.asObservable();
public set(newValue: any): void {
this.subject.next(newValue);
}
}
then your component can register to observable
to render it e. g. by using
public readonly value: Observable<any> = this.stateService.observable
.pipe(map(_ => JSON.stringify(_)));
and to e. g. print out the value
<p *ngIf="value | async">{{(value | async)}}</p>
and if you are now using set
to update the state the component will be refreshed automatically.
In general I found Angular applications are way easier to understand if your components and your application state are properly separated (remember Model-View-Controller?) so that your components do not contain any state themselves and are only binding the templates to the state via observables so that you do not need to care about refreshes and updates (remember Java Swing listeners?). And the state has a clearly defined interface to be interacted with so that no one fiddles in the internal structure of your application state.
Upvotes: 2