2016-03-09 72 views
0

我想使用角2与firebase和我已经设法推送数据到firebase和得到的后面,但是当我尝试向firebase添加新的数据他们不会反映在.get可观察到的自动 - 必须刷新页面或在路由之间切换,这是正确的行为?如果不是,我应该怎么做,以自动更新新的价值观,因为他们来了?可观察不发射新值

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()); 

    } 
} 

回答

1

事实上,这是正常的,因为你需要订阅child_added事件自动通知当你添加一个元素:

let firebaseRef = new Filebase('https://####.firebaseio-demo.com/resource'); 
firebaseRef.on('child_added', (childSnapshot, prevChildKey) => { 
    childSnapshot.forEach((records) => { 
    this.listItems.push(records.val()); 
    }); 
}); 
+0

有没有没有Firebase库的代码版本?因为我只是使用firebase的其余api。 –

+0

事实上,如果没有这个,当你收到'setResource'的响应时(在'setResource'返回的observable中订阅的回调函数中),你需要明确调用'getResources'方法...希望我能正确理解你的使用案件。 –

+0

我会尝试,谢谢你,但每次调用getResources都不会获取所有数据而不是只添加一个或? –