Angular结合Firebase实时数据库CRUD操作如何删除指定列表项?
问题根源
- 现有
deleteItem()方法未传入当前列表项的唯一标识,this.db.list('items').remove()在无参数调用时会删除items节点下的所有数据,这是删除全部内容的直接原因。 - 无法获取
item.id/item.$key是因为获取列表时使用了valueChanges()方法,该方法仅返回节点的业务数据,不会携带节点的唯一key值。
解决方案
步骤1:修改列表获取逻辑,携带节点key
改用snapshotChanges()获取列表,将每个节点的key映射到返回数据中,参考代码:
import { map } from 'rxjs/operators'; // 替换原有获取items的代码 this.items = this.db.list('items').snapshotChanges().pipe( map(changes => changes.map(c => ({ key: c.payload.key, // 存储节点唯一key ...c.payload.val() // 保留原有业务字段 })) ) );
提示:如果为items定义了TypeScript类型,需要在类型声明中新增
key?: string字段,避免类型校验报错。
步骤2:修改HTML模板,调用删除方法时传入key
<tbody> <tr *ngFor='let item of items | async'> <td>{{item.in}}</td> <td>{{item.des}}</td> <td>{{item.cast}}</td> <td>{{item.tomi}}</td> <td>{{item.ris}}</td> <td> <div class="btn-group"> <button (click)="deleteItem(item.key)" class= "btn btn-danger"> delete </button> </div> <td> </tr> </tbody>
步骤3:修改删除方法,按key删除指定节点
deleteItem(key: string){ this.db.list('items').remove(key); }
内容的提问来源于stack exchange,提问作者ripane
相关产品推荐
相关产品推荐

