如何将Firebase的查询快照转换为其他对象?

时间:2020-05-05 20:00:51

标签: angular typescript firebase google-cloud-firestore rxjs

在以下方法中,我正在从Firebase集合中检索文档。

我设法记录了调用getUserByUserId()时需要返回的值,但是我需要将它们作为User对象返回:

getUserByUserId(userId: string) {
    return of(firebase.firestore().collection("users").where("userId", "==", userId)
      .get().then(querySnapshot => {
        querySnapshot.forEach(doc => {
          console.log("User ID", "=>", doc.data().userId);
          console.log("Username", "=>", doc.data().userName);
          console.log("Mechanic", "=>", doc.data().isMechanic);
          console.log("Location", "=>", doc.data().location);
        })
      }).catch(err => {
        console.log(err);
      }));
  }

这是数据需要遵循的User结构:

import { PlaceLocation } from './location.model';

export class User {
    constructor(
        public id: string,
        public name: string,
        public isMechanic: boolean,
        public email: string,
        public location: PlaceLocation
    ) { }
}

有人可以告诉我如何使用此数据创建User对象并将其作为getUserByUserId()的响应返回吗?

1 个答案:

答案 0 :(得分:2)

使用@angular/fire,您可以执行以下操作

constructor(private firestore: AngularFirestore) {
}

getUserByUserId(userId: string) {

    return this.firestore
      .collection("users", ref => ref.where("userId", "==", userId))
      .get()
      .pipe(
        filter(ref => !ref.empty),
        map(ref => ref.docs[0].data() as User),
        map(data => new User(data, data.location))
      )

}

已更新

如果需要对象实例,则应具有其他类似的构造函数 about object assign

export class User {
    constructor(
        public id: string,
        public name: string,
        public contactNumber: number,
        public isMechanic: boolean,
        public email: string,
        public password: string,
        public address: string,
        public imageUrl: string,
        public location: PlaceLocation
    ) { }

    public constructor(
      init?: Partial<User>,
      initLocation?: Partial<PlaceLocation>) {

        Object.assign(this, init);
        if(initLocation) {
          this.location = new PlaceLocation(initLocation);
        }
    }
}

export class PlaceLocation {
    constructor() { }

    public constructor(init?: Partial<PlaceLocation>) {
        Object.assign(this, init);
    }
}

因为您将数据读取为没有类型的对象,所以只能显式创建一个新的User对象,并使用来自对象的数据为其分配属性

getUserByUserId(userId: string) {

    return this.firestore
      .collection("users", ref => ref.where("userId", "==", userId))
      .get()
      .pipe(
        filter(ref => !ref.empty),
        map(ref => ref.docs[0].data() as User),
        map(data => new User(data, data.location))
      )

}