angularfirebase格式,从firebase中提取数据到数组中。

问题描述 投票:0回答:1

你好,伙计们,我有一个问题,格式化我的Firebase-data的数组

这是我的服务,我从firebase中检索数据。

文件名:子类.服务.ts

export class SubcategoryService {

  subcategoryRef: AngularFireList<any> = null;

  constructor(private db: AngularFireDatabase) {
   this.subcategoryRef = db.list("/subCategory");
  }

  getSubCategoriesById(inp_subCatid: string): Observable<any[]> {
    return this.subcategoryRef.snapshotChanges().pipe(
      take(1),
      map(changes => changes.map(c =>
        ({ key: c.payload.key, ...c.payload.val() })
      ).filter((subCat) =>
        subCat.catid === inp_subCatid
      )
    ));
  }
}

我在下面的文件中调用函数getSubCategoriesById()。

文件名:subcategory.page.ts

    this.SubcategoryService.getSubCategoriesById("cat01")
      .subscribe(subCategories =>
        this.subCat = Object.values(subCategories)
    )

正在检索的对象结构是这样的。

enter image description here有一个数组,在这个数组中,有一个对象,其中我的目标对象是

但我想将数据格式化为以下结构。

[
 alcoholic:{
             active:true,
             ageRating: true,
             catgeory: "cat01"
             ...
            },
 warmdrinks:{
             active:true,
             ageRating: false,
             catgeory: "cat01"
             ...
            },
 softdrinks:{
             active:true,
             ageRating: false,
             catgeory: "cat01"
             ...
            },
]

所以我有一个数组,里面有3个对象。

我的firebase数据库在这种情况下是这样的

enter image description here

希望有人能帮我,如果有人需要更多信息,请告诉我。

javascript arrays angularjs firebase-realtime-database javascript-objects
1个回答
0
投票

我认为你应该使用valueChanges而不是snapshotChanges()

return this.getSubCategoriesList().snapshotChanges().pipe(

return this.getSubCategoriesList().valueChanges().pipe(

valueChanges 返回一个文档数据的 Observable。元数据是被剥离的。

我假设你使用的是Angularfire... ...


0
投票

你可以在最后一个数组映射上添加一个映射到链上,来拾取你想要的属性。

getSubCategoriesById(inp_subCatid: string): Observable<any[]> {
  return this.subcategoryRef.snapshotChanges().pipe(
      take(1),
      map(changes => changes.map(c =>
        ({ key: c.payload.key, ...c.payload.val() })
      ).filter((subCat) =>
        subCat.catid === inp_subCatid
      ).map(({alcoholic,softdrinks,warmdrinks,...rest}) => ({
        alcoholic,softdrinks,warmdrinks
      })
    ));
  }
© www.soinside.com 2019 - 2024. All rights reserved.