【问题标题】:How to get lists items in firebase database如何获取firebase数据库中的列表项
【发布时间】:2020-07-08 23:16:00
【问题描述】:

我有以下数据库结构

我正在尝试做的是让 menulist 嵌套在 Categories 主列表中。获取 Categories 没有问题,但我尝试获取 menulist 的列表。我有空页。

代码

  ngOnInit() {
    this.categories = this.af.list("Categories")

    this.categories.snapshotChanges()
    .pipe(
      map(changes =>
        changes.map(c => ({ $key: c.payload.key, ...c.payload.val() }))
      )
    ).subscribe((data: any) => {
      this.categories = data

      console.log(this.categories);
    })

  }

HTML

<tbody  *ngFor="let item of categories.menulist">
<tr role="row" class="even text-right">
<td class="text-right">{{item.body}}</td>
<td class="text-center">{{item.title}}</td>  
</tr>
</tbody>

知道如何将menu list 嵌套在Categories 主列表中吗?

【问题讨论】:

    标签: angular firebase-realtime-database angularfire2


    【解决方案1】:

    您的menulist 是一个对象,但您需要它是一个数组。

    一种解决方案是在 TypeScript 中将其设为数组。例如:

    subscribe((data: any) => {
        this.categories = data.map(category => {
            const menuKeys = Object.keys(category.menulist || {});
            const menulist = menuKeys.map(menuKey => category.menulist[menuKey]);
            return { ...category, menulist };
        });
        console.log(this.categories);
    });
    

    然后你需要遍历categories 和他们的menulist 项目:

    <tbody>
      <ng-container *ngFor="let category of categories">
        <tr *ngFor="let item of category.menulist" role="row" class="even text-right">
          <td class="text-right">{{item.body}}</td>
          <td class="text-center">{{item.title}}</td>  
        </tr>
      </ng-container>
    </tbody>
    

    另一种解决方案是使用keyvalue pipe,如下所示:

    <tbody>
      <ng-container *ngFor="let category of categories">
        <tr *ngFor="let item of category.menulist | keyvalue" role="row"
                                                    class="even text-right">
          <td class="text-right">{{item.value.body}}</td>
          <td class="text-center">{{item.value.title}}</td>  
        </tr>
      </ng-container>
    </tbody>
    

    我没有测试这些,所以请注意拼写错误。

    也别忘了unsubscribengOnDestroy


    您还询问了如何从某个类别的菜单列表中删除特定项目。

    为此,您需要知道菜单列表项的键。替换

    const menulist = menuKeys.map(menuKey => category.menulist[menuKey]);
    

    const menulist = menuKeys.map(key => ({...category.menulist[key], key}));
    

    然后你就可以了

    this.af.object(`Categories/${category.$key}/menulist/${item.key}`).remove();
    

    【讨论】:

    • 谢谢你的回答,我还有空页面。你想和你分享我在数据库中的数据 json 进行测试吗?
    • 我在控制台中有 json,但在 html 中没有显示。检查链接ibb.co/GQhMLK6
    • 这个给ibb.co/Y0m4b5z,这个给tsibb.co/JjpbNwY
    • 非常感谢,他正在工作,谢谢
    • 我有疑问,而我正在尝试删除 menulist 下的具体项目。我删除了主要类别列表:))。您知道如何删除 menulist 下的具体项目吗? . ibb.co/vk0kRCf
    猜你喜欢
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2020-08-13
    • 1970-01-01
    • 2018-04-17
    • 2010-10-10
    相关资源
    最近更新 更多