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

Angular5中无法从Firebase获取$key,表单下拉框值为空

问题根源

你遇到的问题其实是Firebase Angular SDK的方法特性导致的:你在CategoryService中使用了valueChanges()方法来获取分类数据,这个方法只会返回节点中的原始数据内容,不会包含Firebase节点的元数据(比如$key)。所以当你在模板中尝试访问c.$key时,这个属性根本不存在,自然就会是空值,最终表单提交时category字段显示undefined。

解决方案

要获取到Firebase节点的$key,你需要把valueChanges()替换成snapshotChanges()方法,这个方法会返回包含节点元数据的快照对象,我们可以通过RxJS的映射操作把key和数据合并成一个包含$key属性的对象。

步骤1:修改CategoryService代码

更新getCategories()方法,使用snapshotChanges()并映射处理数据:

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
// 别忘了导入rxjs的map操作符(Angular5对应rxjs5.x版本)
import 'rxjs/add/operator/map';

@Injectable()
export class CategoryService {
  constructor(private db: AngularFireDatabase) { }

  getCategories() {
    return this.db.list('/categories', ref => ref.orderByChild('name'))
      .snapshotChanges()
      .map(changes => {
        // 遍历每个快照,合并key和节点数据
        return changes.map(c => ({ 
          $key: c.payload.key, 
          ...c.payload.val() 
        }));
      });
  }
}

步骤2:模板和组件无需额外修改

你的组件中categories$的使用方式不需要改变,模板里的*ngFor="let c of categories$ | async"和[value]="c.$key"现在就能正确获取到Firebase节点的key值了。

验证效果

现在提交表单后,控制台打印的product对象里,category字段就会显示对应的分类节点key,而不是undefined了。


内容的提问来源于stack exchange,提问作者Joginder Pawan Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:33:57