使用Angular在Firestore中获取文档中的特定字段

时间:2019-01-29 16:53:33

标签: angular firebase

我正在使用Angularfire2在Angular 6中创建一个Web应用程序,并将用户的个人信息(例如名字,姓氏,性别等)保存在Firestore中。

我的用户模型是:

export interface User {
  firstName: string;
  secondName: string;
  firstSurname: string;
  secondSurname: string;
  emailAddress: string;
  gender: string;
  dateOfBirth: Date;
}

export interface UserId extends User {
  id: string;
}

我有一个名为FirestoreService的服务,

export class FirestoreService {

  usersCollection: AngularFirestoreCollection<User>;
  userDocument: AngularFirestoreDocument<User>;
  users: Observable<User[]>;

  constructor(
    private afs: AngularFirestore
  ) {
    // Users
    this.usersCollection = afs.collection<User>('users');
    this.users = this.usersCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data() as User;
        const id = a.payload.doc.id;
        return {id, ...data};
      }))
    );
  }

  getUser(uid: string) {
    return this.usersCollection.doc(uid).get();
  }
}

我也尝试过:

getUser(uid: string) {
    this.usersCollection.doc(uid).ref.get().then(doc => {
      if (doc.exists) {
        return doc.data();
      } else {
        return null;
      }
    }).catch(err => {
      console.log(err);
    });
  }

在我的组件内部,我特别需要用户的 firstName 在屏幕上显示它,但是,如果我能抓住所有信息,那就更好了。

在我的组件中,我有:

export class UserProfileComponent implements OnInit {

  userData: any;
  firstName: string;
  firstSurname: string;

  constructor(private firestoreService: FirestoreService) {
  }

  ngOnInit() {
    this.userData = this.firestoreService.getUser('WeGPHreNXIefLwsBsJpRj4txO4S2');
    console.log(this.userData);
  }
}

现在,我在控制台中得到的只是奇怪的东西,而不是用户的任何真实数据。我尝试将服务的getUser方法更改为此:

getUser(uid: string) {
    return this.usersCollection.doc(uid).valueChanges();
}

我想要的是能够访问用户的信息以在我的组件模板中显示该信息,例如:{{firstName}}或使用我的模型,例如{{user.firstName}},我不确定哪个是最好的方法。我在论坛上看到了其他解决方案,但似乎没有一个对我有帮助。

0 个答案:

没有答案