javascript - Observable 不发出新值

标签 javascript typescript firebase angular rxjs

我正在尝试将 Angular 2 与 Firebase 一起使用,并且我已成功将数据推送到 Firebase 并返回,但是当我尝试将新数据添加到 Firebase 时,它​​们不会自动反射(reflect)在 .get 可观察中 - 必须刷新页面或在路线之间切换,这是正确的行为吗?如果不是,我应该怎么做才能在新值出现时自动更新 View ?

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

  }
}

最佳答案

事实上,这很正常,因为您需要订阅 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());
  });
});

关于javascript - Observable 不发出新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35890429/

相关文章:

javascript - 使用 addthis 动态设置 Facebook 共享标题和描述

node.js - Typescript 2.2 Express req, res implicitly any

javascript - 令人困惑的编译器错误 : Argument of type 'string' is not assignable to parameter of type

firebase - 在 Firebase 中强制执行用户配额

ios - 调用 Firebase Observer 后重新加载 TableView

javascript - 遍历 HTML 内容并将值作为全局变量返回

javascript - 我怎样才能像斯坦福专业页面那样制作动画?

javascript - 处理空数组有困难

javascript - Angular 7 响应解析器无法正常工作

javascript - 如何在云函数中使用 indexOn 从实时数据库中检索数据