Reputation: 181
I have this code here that I've set up with Ionic. Everything runs fine. I am able to log out my results from Firebase to the console, but when I assign them to ngFor list they are still undefined it seems from looking at the list. For some reason they are not updating. Is there way I can cause the UI to update once I've gotten some async data back from a server.
import { Injectable } from 'angular2/core';
import { Observable } from 'rxjs/Rx';
@Injectable()
var ref = new Firebase('https://myapi.firebaseio.com');
declare var Firebase;
export class NewsService {
constructor() {
}
get(source) {
return new Observable(observer => {
ref.once('value', snapshot => {
observer.next(snapshot.val().News[source]);
observer.complete();
});
});
}
}
/*~~~~~~~~~~~~~~~*///Other file///*~~~~~~~~~~~~~~~*/
import {Page, NavController, NavParams} from 'ionic-framework/ionic';
import { NewsService } from '../../shared/services/news-service';
@Page({
templateUrl: 'build/pages/news/news.html',
provider: [NewsService]
})
export class News {
items: Array<{title: string, src: string, href: string, alt: string}>;
constructor(private nav: NavController, navParams: NavParams, newsService: NewsService) {
var subscription = newsService.get('businesstech').subscribe(
val => this.items = val,
err => console.log(err),
() => {
subscription.unsubscribe();
}
)
}
}
<ion-navbar *navbar>
<button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>News</ion-title>
</ion-navbar>
<ion-content>
<ion-list>
<ion-item *ngFor="#item of items">
<ion-thumbnail>
<img src={{item.src}}>
<h2>{{item.title}}</h2>
<p>{{item.atl}}</p>
<button clear item-right (click)="open(item.href)">Open</button>
</ion-thumbnail>
</ion-item>
</ion-list>
</ion-content>
Upvotes: 1
Views: 1521
Reputation: 658263
In addition to @ThierryTemplier s great answer:
Angular code runs within Angulars zone which is patched so Angular knows when to run change detection.
When code that runs outside Angulars zone, like in your case when new Firebase()
is initialized outside Angulars code, it runs outside the zone and Angular doesn't recognize model changes.
Running it from the constructor of an Angular component (or somewhere else from withing Angular directives, services, ...) fixes it.
See also Triggering Angular2 change detection manually
Upvotes: 0
Reputation: 202346
The ref
variable is created outside the Angular2 context. You should initialize it within the constructor of the service:
export class NewsService {
constructor() {
this.ref = new Firebase('https://myapi.firebaseio.com');
}
(...)
}
Upvotes: 2