Reputation: 5343
I am trying to use angular 2 with firebase and i have managed to push data to firebase and get the back but when i try to add new data to firebase they are not reflected in the .get observable automatically - have to refresh page or switch between routes, is this the correct behavior? if not what should i do to automatically update view with new values as they come?
import { Component, OnInit } from "angular2/core";
import { FirebaseService } from "../shared/firebase.service";
import { ArcItem } from "./arc-item.model";
import { Observable } from "rxjs/Observable";
import { KeysPipe } from "../shared/keys.pipe";
@Component({
selector: "arc-list",
template: `
<ul class="arc-list">
<li *ngFor="#item of listItems | async | keys" class="arc-item">
<h3>{{ item.name}}</h3><a [href]="item.resourceUrl" target="_blank" class="btn btn-success pull-right"><span>Go</span></a>
<hr>
<blockquote>{{ item.description }}</blockquote>
<hr>
</li>
</ul>
`,
pipes: [KeysPipe]
})
export class ArcListComponent implements OnInit {
listItems: Observable<any[]>;
constructor(private _firebaseService: FirebaseService) {}
ngOnInit(): any {
this.listItems = this._firebaseService.getResources();
}
}
firebase.service
import { Injectable } from "angular2/core";
import { Http } from "angular2/http";
import { ArcItem } from "../arc/arc-item.model";
import "rxjs/Rx";
@Injectable()
export class FirebaseService {
constructor(private _http: Http) {}
setResource(id: number, title: string, description: string, resourceUrl: string) {
const body = JSON.stringify({ id: id, title: title, description: description, resourceUrl: resourceUrl});
return this._http
.post("https://#####.firebaseio.com/resource.json", body)
.map(response => response.json());
}
getResources() {
return this._http
.get("https://#####.firebaseio.com/resource.json")
.map(response => response.json());
}
}
Upvotes: 0
Views: 177
Reputation: 202346
In fact, it's normal since you need to subscribe to the child_added
event to be automatically notified when you add an element:
let firebaseRef = new Filebase('https://####.firebaseio-demo.com/resource');
firebaseRef.on('child_added', (childSnapshot, prevChildKey) => {
childSnapshot.forEach((records) => {
this.listItems.push(records.val());
});
});
Upvotes: 1