Firebase Angularfire2 checks if user exists in database

I have a database with two objects. It looks like this:

users - KEY login: "xexe" password: "123" - KEY login: "dede" password: "123" 

Now I check if the user exists in the database

  constructor(private af: AngularFire) { this.users = af.database.list('/users'); } registerUser(login: string, password: string) { this.af.database.list('/users', { query: { orderByChild: 'login', equalTo: login } }).subscribe(response => { if(response.length === 0) { console.log("User does not exist"); //here i will add a user } else { console.log("Users exists"); } }) } 

What is the problem?

Try registering a user with the name "dede" (the user must exist)

When I click the submit button for the first time, the console shows: Users exists → well, which is good.

The problem is that I click the submit button a second time (without refreshing the webpage)

Then console.log shows me two messages

 User does not exist User exists 

and this will add a new user, which should not be done. Why is the second time the subscription function goes through each line? How to fix it?

+6
source share
1 answer

Instead of using a query, you can structure your data to use the login property, as they are KEY .

 { "users": { "dede": { "login": "dede", "password": "Do not store passwords :)" }, "xexe": { "login": "xexe" } } } 

Now you can create a link to this location and check if the object exists.

 registerUser(login: string, password: string) { const user = this.af.database.object(`users/${login}`); user.subscribe(data => { if(data.$value !== null) { console.log('User does not exist'); } else { console.log('User does exist'); } }); } 
+9
source

All Articles