如何从FirebaseListObservable查询返回单个FirebaseObjectObservable

时间:2017-11-14 02:51:00

标签: angular firebase firebase-realtime-database

我正在使用Angular 4和Firebase Realtime DB构建游戏。我有这样的Firebase DB布局:

FB -> player_list-> -KyagqWEM-cqUoppGe_x
                        id:33061
                        name:Joe
                   -KyadrWSD-aqUeedBv_w
                        id:22037
                        name:Cara

在我的应用中,我想在特定播放器上创建一个FirebaseObjectObservable,本例中为Joe。在我的Ng数据库服务中,我创建了一个如下所示的方法:

getPlayerFromId(playerId: number): FirebaseListObservable<Player[]> {
  this.player = this.database.list(this.playerBasePath, {
    query: {
      orderByChild: 'id',
      equalTo: playerId,
      limitToFirst: 1
    }
  })
  return this.player;
}

查询似乎是在我的Firebase数据库中查找特定节点的最佳方式,遗憾的是查询似乎只返回一个列表,即使该列表只有一个项目的长度。在我的组件中获取一个玩家对象相当容易,代码如下:

  getPlayer(playerId: number){
    this.studentService.getPlayerFromId(playerId)
    .subscribe(data => {
      this.player = data[0];
    })
  }

是否有更优雅的方法从列表查询中返回一个FirebaseObjectObservable?我尝试过映射和过滤,但FirebaseListObservable显然不支持这些。

2 个答案:

答案 0 :(得分:0)

因为返回的结果是一个列表,你需要循环来获取对象

getPlayer(playerId: number){
this.studentService.getPlayerFromId(playerId)
.subscribe(data => {
  data.forEach(player => {
    this.player = player;
  })

 })
}

选中此answer

答案 1 :(得分:0)

    Try with forEach but as this.player will get its data asynchronously from firebase

this.player= this.af.database.list(this.playerBasePath);
        this.player.forEach(element => {
            console.log(element);
        });

    Above code you will be iterating before the data actually there. So for this
    you can add the option


     preserveSnapshot: true

        this.studentService.getPlayerFromId(playerId, { preserveSnapshot: true})
            .subscribe(snapshots=>{
                snapshots.forEach(snapshot => {
                  console.log(snapshot.key, snapshot.val());
                });
            })