首页 > 解决方案 > Angular - 更新到 Firebase

问题描述

我想更新表单中的值。问题是,我不确定如何获取表的 firebase 键。我有一个按钮,单击该按钮将在表单上显示值。下一步是进行更改,然后单击更新按钮将其保存到 Firebase。

我已经这样做了,它可以工作,但这绝对不是解决方案,因为它会导致页面出现问题。

 <button *ngFor="let content of educates" id="updateBtn" class="btn btn-light" (click)="Update(content.key)" style="visibility: hidden">Update</button>

获取 Firebase 密钥的最佳方法是什么?

我的组件.ts

Update(key: string) {

    this.educateSrv.getAll();
    let _educate = new Educate();

    _educate.roles = this.Form.value.roles;
    _educate.widgets = this.Form.value.widgets;
    _educate.url = this.Form.value.url;
    _educate.title = this.Form.value.title;
    _educate.status = this.Form.value.uploadWhen;
    _educate.updatedBy = this.currentUser;
    let _date = new Date()
        .toDateString()
        .replace(/^\S+\s/, '');
    _educate.updatedAt = _date;

    this.educateSrv.Update(key, _educate);
}

我的服务.ts

Update(id: string, data:Educate) {
    return this.af.object("/educate/" + id).update(data);
}

提前致谢。

标签: angularfirebasefirebase-realtime-database

解决方案


您可以通过返回数据来获取密钥:

data: any;

readData() {

   this.db.list('listname').snapshotChanges().pipe(map(list => {
       return list.map(items => {
         return {key: items.payload.key, ...items.payload.val()}
       })
    })).subscribe(data => {
       this.data = data;
       });

}

推荐阅读