使用Angular2,angularfire2和Typescript从Firebase对象中获取数据

juf*_*202 12 rxjs firebase firebase-realtime-database angularfire2 angular

我目前正在使用Angular 2和angularFire2进行项目.我的数据库在Firebase中看起来像这样:base:/ data

[{Name:test1},
{Name:test2},
{Name:test3}]
Run Code Online (Sandbox Code Playgroud)

所有商品都有Firebase密钥.

现在我试图用RX中的Observabels从Firebase中获取数据.当我这样做时,我在控制台中获取名称:

let items= af.database.list('/data').map(i=>{return i});
items.forEach(i=>i.forEach(e=>(console.log(e.name))));
Run Code Online (Sandbox Code Playgroud)

输出:test1,test2,test3.一切正常.

但是当我这样做时:

console.log(items.first());
Run Code Online (Sandbox Code Playgroud)

我得到一个FirebaseListObservable.

如何才能从FirebaseListObservable中获取第一个对象?如何编辑列表中的项目?喜欢:

items[0].name=test3
Run Code Online (Sandbox Code Playgroud)

如何从项目中获取Firebase密钥

我如何从列表中的项目获取firebaseKey?

pau*_*els 16

Observables是一个异步数据结构,这意味着您实际上并不知道数据何时可用,您必须订阅Observable并等待数据在next处理程序中可用.

items.first().subscribe(x => console.log(x.name));
Run Code Online (Sandbox Code Playgroud)

此外,a Observable不是静态的,因此您无法将其索引.如果您只需要第一个项目,那么我建议您提取值并使用flatMap+ first+ map组合进行修改.

af.database.list('/data')
  //Convert array into Observable and flatten it
  .flatMap(list => list)
  //Get only the first item in this list
  .first()
  //Transform the value
  .map(({name, firebaseKey}) => ({name: "test3", firebaseKey}))
  //Subscribe to the stream
  .subscribe(x => console.log(x));
Run Code Online (Sandbox Code Playgroud)