我有一个带有 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的数据来自一个带有一点映射/格式的observable:
this.$ref = this.database.list('/items/' + uid);
this.$ref.subscribe(snapshot => { this.map2itemList(snapshot) });
当用户点击离子按钮时,他会弹出一个可以输入新项目的弹出窗口。按“确定”,新条目应显示在列表中,但不保存到firebase。所以我不能使用
this.$ref.push(myNewItem);
因为可观察到数据将直接被提交并且我的视图被更新。 分离这两个行动的好策略是什么?提前谢谢你。
答案 0 :(得分:0)
这是一个可以帮助你的课程。它有点难看,没有经过测试,但应该有效。
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(),以便将快照作为参数并返回映射的项目,而不是设置内容。
现在您可以创建该类的实例:
let items = new ObservableFirebaseListWithTempStorage(this.$ref, this.map2itemList);
this.itemList = items.items;
添加一个项目:
this.items.addItem(yourNewTempItem);
并将项目保存到db:
this.items.saveItems();