jeudi 26 mars 2020

Angular 8+ Observable - Pattern to update underlying value?

I have a question about using Observables in Angular 8/9. My template uses the async pipe on an observable object, which is great for displaying data. But what if I want to update it? I'm looking for a good-practice pattern here.

One of my work applications has a service that communicates with an HTTP server to get an Observable. It turns that observable into a BehaviorSubject, and publishes its own observable of the BehaviorSubject. The component injects the service, gets a local copy of the observable, and the template reads its value with the async pipe. The template has an event handler that allows an edit; the component's function calls a "mutate" method on the service, which updates the subject's value, and calls .next() on it.

This seems like a lot of extra work, and I was wondering if there was perhaps a better pattern to follow. When I asked about this pattern at work, I was told that angular handles updating from observables better than plain old objects.

Thanks!

Shortened code examples:

Model:

public class Person {
    firstName: string;
    lastName: string;
}

Service:

public class PersonService {
    private personSubj: BehaviorSubject<Person>(null);
    public person$: Observable<Person> = this.personSubj.asObservable();

    public mutateFirstName(newName: string): void {
        this.personSubj.value.firstName = newName;
        this.personSubj.next(this.personSubj.value)
    }

    private getFromHttp(): void {
        this.http.getPerson().subscribe(p => this.personSubj.next(p));
    }
}

Component:

public class PersonComponent {
    // personService is injected in constructor
    this.person$ = this.personService.person$;
}

Template:

 <div *ngIf="(person$ | async) as person">
    <input value="person.firstName" (click)="mutateFirstName('Sam')" />
 </div>

Aucun commentaire:

Enregistrer un commentaire