I have a list that should include only elements with a different name. I selected a list and not an object because I want to display the list with ngFor
create(modul:Modul):Promise<boolean> {
let promise = new Promise<boolean>((resolve, failed) => {
this.af.database.list('/moduls').subscribe(values => {
let found= values.filter((value: Modul) => {
return value.name == modul.name;
});
if(found.length > 0)
failed(false);
else
resolve(true);
})
});
return promise;
}
The problem is that the subscribe part runs n times for n elements. So in the first run there is only the first element in the values array. It will be compared and returns a true or false by ignoring the rest of the list. I think I have to load the whole list first and then check if the name is still included.
Another solution would be to work with an object and setting the name as the key. But I found no way to iterate over this object with an ngFor loop...
I think you should do something like:
const promise = this.af.database.list('/moduls', { query: { orderByKey: name, equalTo: modul.name}, preserveSnapshot: true }).then((snapshot) => {
if(snapshot.exists()) {
console.log('Error an item with that name already exists');
} else {
// push the item onto the list
}
} );
On the OnDestroy() method put this :
promise.subscribe().unsubscribe() ;
it's work perfectly for me .
@cre8 Do you remember how you solved this?