简体   繁体   English

AngularFire检查值是否存在,如果不存在,则创建它

[英]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. 我是AngularFire的新手,在更新AngularFire5之后,我遇到了一些问题。 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. 我要创建一个“房间”,该房间将具有id:name,因此在用户输入名称之后,我将检查数据库是否存在该名称,如果不存在,则将创建一个。 I am adding InfoMessages to specify if the room is created or not. 我正在添加InfoMessages以指定是否创建会议室。

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? 因此,我如何告诉可观察对象一旦创建就必须停止?

You can unsubscribe once the data is inserted, inside your createNewGame function, 插入数据后,您可以在createNewGame函数中取消订阅,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM