Angular2 Observed List

I am facing some problems in my Ionic application (data is updated asynchronously, but the UI is not updated accordingly). I have scratched this issue for a long time and am now trying to test a different approach: using Observables . But I'm not sure how to implement it. Tutorials with Observables are the focus of using the Http service, which already returns an Observable . My scenario is as follows:

I have a DataService containing a list of Person objects. The service has a receiver that returns this list.

 export class DataService { private _list: Person[] = []; get list(): Person[] { return this._list } } 

Earlier, I directly used this list in my components:

 <ion-list> <ion-item *ngFor="let person of dataService.list"> {{person.name}} </ion-item> </ion-list> 

Now I want to add another getter to the DataService , which will instead return the Observable to the Person[] list. I do not know what:

  • How and where to define an Observable for a list. Do I define the Observable property as a DataService property and initialize it in the constructor or return a new Observable directly from the service recipient? And how do I wrap a list in Observable ?
  • How to use this Observable getter in my component? * NgFor = "???"
  • When a list changes asynchronously, how do I signal an Observable that a list has been changed?

I hope this solves my problems with updating the user interface.

+5
source share
1 answer

Calculated =)

DataService

 export class DataService { private _list: Person[] = []; private _observableList: BehaviorSubject<Person[]> = new BehaviorSubject([]); get observableList(): Observable<Person[]> { return this._observableList.asObservable() } add(person: Person) { this._list.push(person); this._observableList.next(this._list); } } 

Component Template

 <ion-list> <ion-item *ngFor="let person of dataService.observableList | async"> {{person.name}} </ion-item> </ion-list> 

Get help from here:

https://dzone.com/articles/how-to-build-angular-2-apps-using-observable-data-1 https://github.com/jhades/angular2-rxjs-observable-data-services https: //coryrylan.com/blog/angular-2-observable-data-services

+8
source

All Articles