Firebase/AngularFire2: 不直接推送数据,只有在按下保存按钮后

Firebase/AngularFire2: Push data not directly, only after pressing the save-button

我有一个带有 Ionic 离子列表的配置屏幕,用户可以在其中向列表添加项目,并且还会显示列表的当前条目.我希望用户能够通过按钮添加新项目。新项目不应立即保存到 firebase - 用户必须按保存按钮才能执行此操作。目前我的代码看起来像这样

  <ion-list *ngIf="regimeList">
    <ion-list-header color="secondary">Items
      <button class="my-select" ion-button outline item-end (click)="addItem()">+</button>
    </ion-list-header>
      <ion-item *ngFor="let item of itemList">
        {{item.name}}
      </ion-item>
  </ion-list>

itemList 的数据来自带有一点 mapping/formating:

的可观察对象
this.$ref = this.database.list('/items/' + uid);
this.$ref.subscribe(snapshot => { this.map2itemList(snapshot) });

当用户单击离子按钮时,他会看到一个弹出窗口,他可以在其中输入新项目。按 "ok" 时,新条目应显示在列表中,但不会保存到 firebase。所以我不能使用

this.$ref.push(myNewItem);

由于可观察,数据将直接提交并更新我的视图。 将这两个动作分开的好策略是什么?提前谢谢你。

这里有一个 class 可以帮助你。它有点难看,没有经过测试,但它应该可以工作。

import { Observable } from 'rxjs';

class ObservableFirebaseListWithTempStorage {
    private observer;
    private tempItems: Array<any>;
    private dbItems: Array<any>;
    public items: Observable<Array<any>>;

    constructor(private $ref, private mapFunction) {
        this.items = Observable.create(observer => {
            this.observer = observer;
        });
        $ref.subscribe(snapshot => {
            this.dbItems = this.mapFunction(snapshot);
            this.updateItems();
        });
    }
    private updateItems(){
        let tempList = [];
        tempList.push(this.dbItems);
        tempList.push(this.tempItems);
        this.observer.next(tempList)
    }
    public addItem(item): void {
        this.tempItems.push(item);
        this.updateItems();
    }
    public saveItems():void{
        this.tempItems.forEach(item=>{
            this.$ref.push(item);      
        });
    };
}

你应该稍微改变你的 map2itemList() 以便它将快照作为参数和 returns 映射的项目,而不是设置一些东西。

现在您可以创建一个实例 class:

let items = new ObservableFirebaseListWithTempStorage(this.$ref, this.map2itemList);
this.itemList = items.items;

添加项目:

this.items.addItem(yourNewTempItem);

并将项目保存到数据库:

this.items.saveItems();