Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Observable List

I'm running into some issues in my Ionic application (data updated asynchronously but UI not updating accordingly). I've scratched my head over this issue for long and now am trying to test a different approach: using Observables. But I'm unsure how to implement it. Tutorials with Observables on the net focus on using 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 getter that returns this list.

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

Earlier on, I was directly using 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 DataService that would return an Observable of the Person[] list instead. What I don't know is:

  1. How and where to define a Observable for the list. Do I define an Observable as a DataService property and initialise it in the constructor or do I return a new Observable directly from the service getter? And how do I wrap the list in an Observable?
  2. How to use this Observable getter in my component? *ngFor="???"
  3. When the list is changed asynchronously, how do I signal to the Observable that the list has been modified?

I'm hoping this will solve my UI-not-updating issues.

like image 270
AweSIM Avatar asked Jun 16 '16 21:06

AweSIM


1 Answers

Figured it out =)

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>

Got 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

like image 55
AweSIM Avatar answered Sep 19 '22 18:09

AweSIM