Firebase / AngularFire2: click data directly, only after clicking save

I have an Ionic ion list configuration screen where the user can add items to the list, and the current list entries are also displayed. I want the user to be able to add new items using the button. new items should not be immediately saved in firebase - the user must click the save button to do this. currently my code is as follows

<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> 

the data for itemList refers to the observable with a little display / shaping:

 this.$ref = this.database.list('/items/' + uid); this.$ref.subscribe(snapshot => { this.map2itemList(snapshot) }); 

when the user presses the ion button, he receives a pop-up window where he can enter a new element. when you click "ok", the new entry should be displayed in the list, but not saved in firebase. Therefore i cannot use

 this.$ref.push(myNewItem); 

due to the observable, the data will be directly transmitted and my presentation will be updated. What is a good strategy to separate the two? thank you in advance.

+5
source share
1 answer

Here is a class that can help you. This is a little ugly and not tested, but it should work.

 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); }); }; } 

You have to change your map2itemList () a bit, so it takes a snapshot as a parameter and returns the displayed items, rather than setting something.

Now you can instantiate this class:

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

Add an item using:

 this.items.addItem(yourNewTempItem); 

and save the elements in db:

 this.items.saveItems(); 
0
source

Source: https://habr.com/ru/post/1271015/


All Articles