Let's say I'd like to retrieve a set of records from a store, display them in a list using *ngFor
, e.g.
<ul>
<li *ngFor="let record in records | async">
...
</li>
</ul>
Now the user clicks the 'New...' button, another record is added to the store and
recordAdded: EventEmitter<string>;
fires to tell me about the location. So I get that new record - and that record only - from the store and... whoops, how do I get my *ngFor
to display this additional record?
Ok, so I could keep all records in array, for example
_records: Record[];
and fill this array by subscribing to the Observable<Record[]>
like
this.recordService.getAll().subscribe(r => this._records = r);
But this array needs to be an Observable
itself in order to notify consumers when there is a new record. So
observableRecords = Observable.create(obs => {
this.recordService.getAll().subscribe(rec => {
this._records = rec;
obs.next(rec);
// Got the array published, now waiting for events
this.recordAdded.subscribe(rec => {
this._records.push(rec);
obs.next(this._records);
});
});
});
Ugh... Not only is this excruciating to look at, there's also a ton of overhead as the whole array gets re-published every time a new record is added and - most likely - Angular 2 will re-build the whole list from scratch at every turn.
Since this is such a common scenario I imagine there must be a much better way to do this.