我有一个带有 的配置屏幕 ionic ion-list,用户可以在其中向列表中添加项目,并且还显示列表的当前条目。我希望用户能够通过按钮添加新项目。新项目不应立即保存到 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) });
当用户点击 ionic 按钮时,他会得到一个弹出窗口,他可以在其中输入一个新项目。按“确定”后,新条目应显示在列表中,但不会保存到 firebase。所以我不能使用
this.$ref.push(myNewItem);
由于可观察,数据将被直接提交并更新我的 View 。
将这两个 Action 分开的好策略是什么?先感谢您。
最佳答案
这是一个可以帮助你的类(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() 以便它将快照作为参数并返回映射的项目,而不是设置某些内容。
现在您可以创建该类的实例:
let items = new ObservableFirebaseListWithTempStorage(this.$ref, this.map2itemList);
this.itemList = items.items;
添加一个项目:
this.items.addItem(yourNewTempItem);
并将项目保存到数据库:
this.items.saveItems();
关于Firebase/AngularFire2 : Push data not directly, 仅在按下保存按钮后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45773502/