6

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

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

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

Now I'm checking if 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's the problem?

Let's try to register a user with "dede" login (user should exists)

When I click a submit button first time, the console shows: Users exists -> well, that's good.

The problem is when I click the submit the second time (without refreshing webpage)

Then console.log shows me two messages

User does not exist
User exists

and that would add a new user what shouldn't be done. Why the second time the subscribe function iterate through every row? How to fix it?

4

1 回答 1

9

您可以构造数据以使用login属性,而不是使用查询KEY

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

现在您可以创建对此位置的引用并检查对象是否存在。

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');
    }
  });
}
于 2016-07-18T13:15:12.737 回答