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:
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
?Observable
getter in my component? *ngFor="???"Observable
that the list has been modified?I'm hoping this will solve my UI-not-updating issues.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With