Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript FireStore查询单个文档_Javascript_Angular_Angularfire2_Google Cloud Firestore - Fatal编程技术网

Javascript FireStore查询单个文档

Javascript FireStore查询单个文档,javascript,angular,angularfire2,google-cloud-firestore,Javascript,Angular,Angularfire2,Google Cloud Firestore,背景:我试图用一个值而不是ID从集合中检索一个文档。我基本上是在尝试建立一个登录系统 我尝试了这个解决方案: 使用flat map to和limit(1)执行此操作,但它似乎没有提供任何信息,这就是我的代码现在的样子: this.user = this.afs.collection('users/', ref => ref.where('username', '==', this.username).limit(1)).valueChanges().flatMap(result

背景:我试图用一个值而不是ID从集合中检索一个文档。我基本上是在尝试建立一个登录系统

我尝试了这个解决方案:

使用flat map to和limit(1)执行此操作,但它似乎没有提供任何信息,这就是我的代码现在的样子:

this.user = this.afs.collection('users/', ref => ref.where('username',
      '==', this.username).limit(1)).valueChanges().flatMap(result => result);
    console.log(this.user.username);

输出是未定义的,但是如果我只打印用户,我确实得到了可观察的

,您应该将此设置为
。用户
到可观察的引用,然后像这样订阅它:

this.user = this.afs.collection('users', (ref) => ref.where('username', '==', this.username).limit(1)).valueChanges();
// I removed the slash after 'users' as it isn't necessary
 this.user = this.afs.collection('users', 
  (ref) => {
    return ref.where('username', '==', this.username).limit(1)
  })
  .snapshotChanges()
  .map((users) => {
    return users.length
  });
然后像这样订阅可观察到的内容:

this.user.subscribe((user) => {
 console.log(user);
});
这只会给你一个结果。控制台记录可观察对象不会显示数据,而是记录可观察对象

请注意,您应该拥有与该用户名相关的userId,并取而代之地获取文档,因为它比获取与字段匹配的集合并将其限制为1更安全、更明确。如果这是身份验证问题,您应该使用Firebase Auth,并使用任何形式的身份验证作为用户名,Firebase Auth将处理没有重复登录的问题。如果希望使用用户名而不是电子邮件,您可以请求,但您的方法应该只返回请求的长度,如下所示:

this.user = this.afs.collection('users', (ref) => ref.where('username', '==', this.username).limit(1)).valueChanges();
// I removed the slash after 'users' as it isn't necessary
 this.user = this.afs.collection('users', 
  (ref) => {
    return ref.where('username', '==', this.username).limit(1)
  })
  .snapshotChanges()
  .map((users) => {
    return users.length
  });
这样,您就不会在请求中返回用户对象,而是返回一个数字,如果该数字大于零,则表示用户已经拥有该用户名


由于您使用的是
valueChanges()
而不是
snapshotChanges()
,因此在DOM上显示数据之前似乎不需要操作数据,因此您不需要订阅数据,而是使用标记中的异步管道订阅可观察数据。这是我前几天问的一个问题,它解释了您的问题以及在标记中使用异步管道:

您如何在html中显示它?