You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular解析Firebase实时数据库数组渲染列表遇NG02200错误求助

解决方案

1. 修改Firebase服务代码(firebase.service.ts)

将获取节点的方法从db.object()改为db.list(),因为目标节点是数组类型,list()专门用于处理列表数据:

GetNotificationUsers() { 
  return this.db.list(this.customerId + "/mailservice/users"); 
}

2. 调整组件订阅逻辑(component.ts)

list()的snapshotChanges()返回包含节点元数据的数组,需要提取实际用户数据:

getNotificationUsers() { 
  this.firebase.GetNotificationUsers().snapshotChanges().subscribe((data) => { 
    this.notificationUsers = data.map(item => {
      return item.payload.val() as users;
    });
    console.log(this.notificationUsers);
  }); 
}

3. 修正模板语法错误(component.html)

原模板中最后一个<tr>未闭合,修正后:

<table class="table">
  <thead>
    <tr>
      <th scope="col">Id</th>
      <th scope="col">Name</th>
      <th scope="col">Mailaddresse</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of notificationUsers">
      <th scope="row">{{user?.id}}</th>
      <td>{{user?.name}}</td>
      <td>{{user?.email}}</td>
    </tr>
  </tbody>
</table>

(可选)不修改服务的替代方案

如果坚持使用db.object(),可在组件中将返回的对象转换为数组:

getNotificationUsers() { 
  this.firebase.GetNotificationUsers().snapshotChanges().subscribe((data) => { 
    let a = data.payload.toJSON(); 
    this.notificationUsers = Array.isArray(a) ? a : Object.values(a) as users[];
    console.log(this.notificationUsers);
  }); 
}

错误原因说明

  • Firebase实时数据库中,数组节点需用AngularFireList(db.list())获取,db.object()仅适用于单个对象节点。
  • 用db.object()获取数组节点时,返回的快照数据可能被解析为非可迭代的对象,导致*ngFor无法遍历,触发"Cannot find a differ supporting object"错误。

内容的提问来源于stack exchange,提问作者Markus Wimmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 18:07:13