可观察到不会发出新值

时间:2016-03-09 11:32:32

标签: javascript typescript firebase angular rxjs

我正在尝试使用带有firebase的angular 2并且我已设法将数据推送到firebase并获得后退但是当我尝试向firebase添加新数据时,它们不会自动反映在.get observable中 - 必须刷新页面或者在路线之间切换,这是正确的行为吗?如果不是我应该做什么来自动更新视图与新值?

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 个答案:

答案 0 :(得分: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());
  });
});