【问题标题】:angular/firebase format retrieved data from firebase into arrayangular/firebase 格式将数据从 firebase 检索到数组中
【发布时间】:2020-08-17 10:32:57
【问题描述】:

大家好,我在将 firebase 数据格式化为数组时遇到问题

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

文件名:subcategory.service.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)
    )

我正在检索的对象的结构看起来像这样

有一个数组,其中有一个对象,其中我的目标对象是

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

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

这样我就有了一个里面有 3 个对象的数组。

我在这个案例中的 firebase 数据库看起来像这样

希望有人可以帮助我,如果有人需要更多信息,请告诉我

【问题讨论】:

    标签: javascript arrays angularjs firebase-realtime-database javascript-objects


    【解决方案1】:

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

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

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

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

    我假设你正在使用 Angularfire...

    【讨论】:

    • 嗨@LeranToday,我用更多细节指定了我的问题,就像我把我的构造函数放在里面......我尝试了 valueChanges() 但它没有那么好......
    【解决方案2】:

    您可以在最后一个数组映射的链中添加一个映射以获取您想要的属性:

    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
          })
        ));
      }
    

    【讨论】:

    • 但是如果“catid”匹配另一个类别,例如“食物”类别,该怎么办?酒精饮料、温饮料和软饮料不再匹配,将会出现新的子类别,如汤、三明治……所以我也必须更改我的代码,这就是我不想要的。我希望这动态发生。我希望你能理解我的想法
    • 我有点困惑。也许如果您提供一些用例(数据示例)来展示它们如何到达客户端以及您希望它如何,那么展示起来会更容易。
    猜你喜欢
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    相关资源
    最近更新 更多