首页 > 解决方案 > 从 Angular 组件中的 Firebase 访问值

问题描述

我有名字和姓氏分开的用户文件。我需要在组件中访问它们,然后将它们合并,这样我就可以将整个名称保存在另一个集合中。到目前为止,我只发现过时版本的损坏或弃用代码。 https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md 使用此代码,我无法访问组件。如何将值存储在组件中的变量中以便我可以使用它们?

export interface user {
 first_name: string;
 last_name: string;
}
export class UserComponent {

 userCollection: AngularFirestoreCollection<user>;
 firstname: string;
 lastname: string;

 constructor(private afs: AngularFirestore) {
    this.userCollection.doc(this.user).ref.get().then(function(doc) {
    console.log(doc.data());
    *MISSING CODE*
    console.log(this.firstname, this.lastname);
  }
 }

我现在必须使用哪个 .get 或 .ref 或 payload 或 doc.data() 或 .pipe 将来自 firebase 的数据保存在这两个变量“firstname”和“lastname”中,以便我可以在组件中使用它们?我在控制台中得到了整个对象,但不是每个变量都是分开的。我花了 4 天时间才发现 FirestoreCollections 上的“.get()”只有当我在它前面放一个“.ref”时才有效,如果有人能帮助我更快地找到这些信息,那将不胜感激。

标签: angularfirebasecomponents

解决方案


由于 tou 正在获取数据,您可以按如下方式分配它,

 constructor(private afs: AngularFirestore) {
    this.userCollection.doc(this.user).ref.get().then(function(doc) {
    this.firstname = doc.data().first_name;
    this.lastname = doc.data().last_name;    
    console.log(this.firstname, this.lastname);
}

推荐阅读