如何遍历firebase

时间:2017-10-11 05:06:03

标签: angular firebase firebase-realtime-database angularfire2

我还是firebase的新手,我不知道如何在 item.compactReports 中提取对象数组,然后将其显示在我的 home.component.html

注意:compactReports的长度也是未知的,它因每个节点而异。

compactReports = [{" area":{" 0":"一些数据;更多数据"}},...,{"详细信息":{" 0":"某些数据"}}}

我希望输出结果如下:

 <td> area: some data <br> 
  ....(some more lines depends on each object)...<br>
      detail: some data <br>
 </td>

home.component.ts

export class HomeComponent implements OnInit {
  reports$; 
  constructor(angularData: AngularFireDatabase,homeService: HomeService) {
    this.reports$ = homeService.getData();  
   } 
}

home.component.html

<tr *ngFor="let item of reports$ | async">
                <td>{{item.type}}</td>
                <td>{{item.compactReports}}</td> // ***stuck here
                <td>latitude:{{item.latitude}}<br>
                     longitude:{{item.longitude}}</td>
                <td>{{item.phoneNumber}}</td>
                <td>{{item.timestamp}}</td>
              </tr>

home.service.ts

export class HomeService {
  constructor(private db: AngularFireDatabase) { }

  getData(){
    return this.db.list('/Reports');

  }
}

My data structure in firebase

1 个答案:

答案 0 :(得分:0)

这是我的解决方案。鉴于'reports $'是一个项目对象数组,每个项目的'compactReports'是一个键值对数组,你可以定义一个自定义函数(我将它命名为'listDetails')来评估'compactReports'并操纵结果。请注意,Angular interpolation {{...}}将结果输出为纯文本,因此如果需要显示html标记,则需要属性[innerHtml]。

home.component.ts

export class HomeComponent implements OnInit {
    ......

    listDetails( compactReports : {}[] ) {
        let result : string = "";
        for (let i in compactReports) {
            let keys = Object.getOwnPropertyNames(compactReports[i]);
            for (let j = 0; j < keys.length; j++) {
                result += keys[j] + ": " + compactReports[i][keys[j]] + "<br>";
            }
        }
        return result;
    }
}

home.component.html

<tr *ngFor="let item of reports$ | async">
    ......

    <td [innerHtml]="listDetails(item.compactReports)"></td>

    ......
</tr>