如何从Firebase获取嵌套的json数据?

时间:2019-11-29 06:58:19

标签: angular firebase

我想根据来自实时数据库的数据创建一个下拉菜单。 我写了几行代码,但无法获取子类别 创建了一个界面

export interface MenuInfo {
  name: string;
  subcategory?: MenuInfo[];
}
  menuList: MenuInfo[] = [];

  constructor(public dataService: DataService) {}

  ngOnInit() {
    this.getMenuList();
  }

  getMenuList() {
    this.dataService.getMenuList().subscribe(data => {
      this.menuList = this.dataService.snapShotToArray(data);
      console.log("menulist"+ this.menuList[0].subcategory);
    });
  }
  getMenuList() {
    return this.fdb.list('category').snapshotChanges();
  }
  snapShotToArray(snapShot) {
    let retArr: any[] = [];
    snapShot.forEach(element => {
      let obj: any = {};
      obj = element.payload.val();
      obj.key = element.key;
      retArr.push(obj);
    });

    return retArr;
  }

这是来自Firebase的json数据。

category
   -LtygKwodI5HdptwuInj
     name: "Helmet"
     subcategory
       -LtygbtNUgCPC4paDswy
          name: "full-face"

我应该如何创建下拉菜单。 enter image description here

1 个答案:

答案 0 :(得分:0)

检索key后,添加对节点subcategory的引用,订阅可观察对象,然后使用forEach您可以在子类别中访问name的值:

snapShot.forEach(element => { 
  let lists = this.fdb.list("category/"+element.key+"/"+"subcategory").snapshotChanges();
  lists.subscribe(data => { 
    data.forEach(subElem => {
      console.log(subElem);
  });
 });
});