简体   繁体   English

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

[英]Getting Data out of Firebase Object with Angular2, angularfire2 and Typescript

Im currently working on a Project with Angular 2 and angularFire2. 我目前正在使用Angular 2和angularFire2进行项目。 My database looks like this in Firebase: base:/data 我的数据库在Firebase中看起来像这样:base:/ data

[{Name:test1},
{Name:test2},
{Name:test3}]

All of the items also have the Firebase key. 所有商品都有Firebase密钥。

Now im trying to get data out of the Firebase with the Observabels from RX. 现在我试图用RX中的Observabels从Firebase中获取数据。 When i do this, i get the names in the Console: 当我这样做时,我在控制台中获取名称:

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

Output: test1,test2,test3. 输出:test1,test2,test3。 Everything Works. 一切正常。

But when i do this: 但是当我这样做时:

console.log(items.first());

I get a FirebaseListObservable back. 我得到一个FirebaseListObservable。

How can i get only the First Object from the FirebaseListObservable? 如何才能从FirebaseListObservable中获取第一个对象? How can i edit Items in the list? 如何编辑列表中的项目? like: 喜欢:

items[0].name=test3

And How can i get the Firebase Key from an Item 如何从项目中获取Firebase密钥

how can i get The firebaseKey from an Item in the list? 我如何从列表中的项目获取firebaseKey?

Observables are an asynchronous data structure, meaning that you don't actually know when the data is going to be available, you have to subscribe to the Observable and wait for the data to become available in the next handler. Observables是一种异步数据结构,这意味着您实际上并不知道数据何时可用,您必须订阅Observable并等待数据next处理程序中可用。

items.first().subscribe(x => console.log(x.name));

Further, an Observable is not static, so you can't index into it as such. 此外, Observable不是静态的,因此您无法将其索引。 If you need only the first item then I would suggest instead that you extract the value and modify it with a flatMap + first + map combination. 如果您只需要第一个项目,那么我建议您提取值并使用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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM