Search code examples
angularfirebase-realtime-databaseionic3angularfireangularfire5

AngularFire check if value exists, if not, create it


I am new on AngularFire, and after the update to AngularFire5 I am having some issues. I want to create a 'room', the one which will have a id:name, so after the user inputs the name, I've check on the database if this name exists, if not, I will create. I am adding InfoMessages to specify if the room is created or not.

Here is my code:

checkIfRoomExistAndCreate(salaName: string, puntuacio: number){
    this.items = this.afDB.list("/game/" + salaName).valueChanges();
    this.items.subscribe((x) => {
        if (x.length === 0) {
            this.createNewGame(salaName, puntuacio);
        } else {
            console.log('This room already exists');
        };
    })
}

The problem is once is checked if there is a room with the same name, after created it, it check again and the error message is displayed.

So, how can I tell to the observable that once is created, it has to stop?


Solution

  • You can unsubscribe once the data is inserted, inside your createNewGame function,

    this.afDB.list("/game/" + salaName).set("player1", this.player1.name);
    this.items.unsubscribe();