Angularfire: Check for duplicates before adding to list

Created on 18 Jul 2016  路  3Comments  路  Source: angular/angularfire

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

All 3 comments

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?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

martinyoussef picture martinyoussef  路  3Comments

itisparas picture itisparas  路  3Comments

KLiFF2606 picture KLiFF2606  路  3Comments

Maistho picture Maistho  路  3Comments

aucevica picture aucevica  路  3Comments