在我的 Angular 应用程序中,我使用 Angularfire2 和 Firestore。
从文档中我知道我可以使用以下命令获取电子邮件“xyz@gmail.com”的用户(其中 db 是 AngularFirestore 的实例):
this.db.collection("users", ref => ref.where('email', '==', "xyz@gmail.com"));
但是,
let user = this.db.collection("users", ref => ref.where('email', '==', "xyz@gmail.com"));
不会将电子邮件“xyz@gmail.com”的用户保存在变量“user”中,而是保存整个集合“users”。
如何获取电子邮件地址为“xyz@gmail.com”的用户? 那么如何获取用户的属性(例如用户的 id)?
<小时/>更新:
我尝试了以下方法:
给出错误消息,表明 AngularFirestoreCollection 类型上不存在属性“then”。
我还尝试了以下方法:
let user = this.db.collection("users", ref => ref.where('email', '==', "xyz@gmail.com"))
.valueChanges()
.pipe(reduce((acc, curr) => curr[0], {}));
这也产生了语法错误。
最后,我简单地尝试了这个:
let users = this.db.collection("users", ref => ref.where('email', '==', "xyz@gmail.com"));
let user = users[0];
console.log(user);
这没有给出语法错误。然而,“用户”是未定义的。
<小时/>更新2:
我也尝试过这个:
private async getUser() {
let users = await this.db.collection("users", ref => ref.where('email', '==', "xyz@gmail.com"));
let user = users[0];
console.log(user);
}
但是,“用户”仍然是“未定义”。
P.S.:firestore 中确实存在电子邮件地址为“xyz@gmail.com”的用户。
<小时/>更新3:
我还尝试了以下方法:
但是,与更新 1 中使用的版本一样,我收到“reduce”错误 ...错误消息显示:
Cannot find name "reduce"
最佳答案
let user = this.db.collection("users", ref => ref.where('email', '==', "xyz@gmail.com"));
不会为您提供一个用户,而是为您提供具有该电子邮件属性的用户集合(数据库中可以有多个用户) 如果你知道你只有一个,我认为你可以使用:
.valueChanges()
.pipe(reduce((acc, curr) => curr[0], {}))
仅获取集合中的第一个元素
关于angular - 如何根据属性从firestore检索用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51678820/