how do you subscribe to changes in an array of objects?

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

state.service.ts

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.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top