如何在Angular中向Firebase实时数据库正确推送数据
解决Angular向Firebase实时数据库添加自定义键数据的问题
Firebase实时数据库的REST API中,POST请求到节点.json路径时,会自动生成随机唯一ID作为数据键,这就是你现在看到随机字符串键的原因。如果要像数据库中前三条那样使用自定义键(如1、2、3)存储数据,需要改用PUT请求,并在URL中指定目标键名。
修改后的代码示例
如果要添加键为4、值为Carrot的数据:
// 指定自定义键,这里用4作为示例,可根据需求修改 const customKey = '4'; this.http.put(`https://farmio-3lbue-default-random-rtdb.firebaseio.com/products/${customKey}.json`, 'Carrot') .subscribe(res => { console.log(res, 'put'); }, error => console.log(error));
关键说明
- 使用
PUT请求时,URL需要明确指定到具体的键路径(如products/4.json),这样数据会直接存储在该键下,不会生成随机ID。 - 如果需要自动递增键值,可以先通过
GET请求获取products节点的所有数据,找到当前最大的键后加1,再用PUT写入新数据。示例如下:
// 获取当前所有产品数据,计算新键 this.http.get('https://farmio-3lbue-default-random-rtdb.firebaseio.com/products.json') .subscribe(products => { if (products) { // 获取所有键并转为数字,找到最大值 const keys = Object.keys(products).map(Number); const newKey = (Math.max(...keys) + 1).toString(); // 写入新数据 this.http.put(`https://farmio-3lbue-default-random-rtdb.firebaseio.com/products/${newKey}.json`, 'Carrot') .subscribe(res => console.log(res, 'put success')); } else { // 若节点为空,从1开始 this.http.put('https://farmio-3lbue-default-random-rtdb.firebaseio.com/products/1.json', 'Carrot') .subscribe(res => console.log(res, 'put success')); } });
内容的提问来源于stack exchange,提问作者Mohan Reddy
相关产品推荐
相关产品推荐

