首页 > 解决方案 > 如何使用 map 运算符将新字段添加到对象中,并将其添加到返回到 Observable 的数组中?

问题描述

我在 RxJS 中很新,并且在 Angular probject 上工作我有以下问题。

在我的组件中,我正在使用此服务方法检索Observable<Patient[]>(它从 Firebase FireStore DB 中检索它):

  getAllPatients(): Observable<Patient[]> { 
   
    return <Observable<Patient[]>> <unknown>this.firestore.collection('patients').snapshotChanges()
    .pipe(
      map(snaps => 
        snaps
          .map(snap => snap.payload.doc)
          .map(doc => ({
            UID: doc.id,
            id: doc.id,
            firstName: doc.get("firstName"),
            surname: doc.get("surname"),
            completeName: `${doc.get("firstName")} ${doc.get("surname")}`,
            birthDate: doc.get("birthDate"),
            placeOfBirth: doc.get("placeOfBirth"),
            socialSecurityCode: doc.get("socialSecurityCode"),
            personalEmail: doc.get("personalEmail"),
            personalPhone: doc.get("personalPhone"),
            occupation: doc.get("occupation"),
            contactReason: doc.get("contactReason")
          }))
      )
    );

  }

其中Patient是如下界面:

export interface Patient {
    firstName: string;
    surname: string;   
    completeName: string;
    birthDate: any; 
    placeOfBirth: string;
    socialSecurityCode: string;
    personalEmail: string;
    personalPhone: string;
    occupation: string;
    contactReason: string;
    birthDateStr?: string;
}

如您所见,它包含以下两个字段:

  1. 出生日期:任何;:它是从 FireStore 中检索的,它是一个日期字段。
  2. 出生日期字符串?:它不是从 FireStore 中检索到的,我必须从以前的birthDate字段作为字符串开始构建它。

所以在我的组件代码中,最初我有这样的东西来检索我的数据(它工作得很好):

// Load the list of all the patients from the DB:
async loadPatientsList() {
    this.patientsList$ = await this.patientService.getAllPatients()
    console.log("patientsList$: ", this.patientsList$);
    //this.loading = false;
}

现在我有一个问题,对于我的 Observable 的Patient[]数组中的每个Patient对象,我必须添加这个birthDateStr?额外字段将当前对象的birthDate字段值设置为字符串。

我认为我必须使用 RxJS 并且我正在尝试这样做:

// Load the list of all the patients from the DB:
async loadPatientsList() {
    this.patientsList$ = await this.patientService.getAllPatients()
        .pipe(
          map(fields => {
            let temp = { ...fields, 
                         birthDateStr: fields.birthDate..... // HERE I DON'T KNOW WHAT TO DO !!!
                       }
            return temp;
          })
        );
    console.log("patientsList$: ", this.patientsList$);
    //this.loading = false;
}

所以基本上我正在尝试使用 RxJS地图运算符来添加这个字段。基本上我正在创建一个全新的临时对象,其中包含原始对象的所有字段

然后我试图创建新的birthDateStr ,从birthDate开始应该包含在原始字段中,通过这一行:

birthDateStr: fields.birthDate..... // HERE I DON'T KNOW WHAT TO DO !!!

问题是现在 IDE 在上一行(在birthDate属性上)给了我以下错误:

'Patient[]'.ts(2339) 类型上不存在属性'birthDate'

为什么?怎么了?我错过了什么?我该如何解决这个问题?此外,我如何才能完成我的代码,以便将此日期字段转换为代表我的日期的字符串?

标签: typescriptrxjs

解决方案


它看起来fields实际上是一组患者:Patient[]

因此,您将需要映射该数组以将新birthDateStr字段添加到每个患者:

// Load the list of all the patients from the DB:
async loadPatientsList() {
  this.patientsList$ = await this.patientService.getAllPatients()
    .pipe(
      map(patients => {
        return patients.map(fields => {
          return {
            ...fields, 
            birthDateStr: fields.birthDate // <-- do whatever conversion you need here
          };
        })
      });
}

也许您可以birthDateStr在您的服务中添加该字段:

getAllPatients(): Observable<Patient[]> {   
  return <Observable<Patient[]>> <unknown>this.firestore.collection('patients').snapshotChanges()
    .pipe(
      map(snaps => 
        snaps
          .map(snap => snap.payload.doc)
          .map(doc => ({
            UID: doc.id,
            id: doc.id,
            firstName: doc.get("firstName"),
            surname: doc.get("surname"),
            completeName: `${doc.get("firstName")} ${doc.get("surname")}`,
            birthDate: doc.get("birthDate"),
            placeOfBirth: doc.get("placeOfBirth"),
            socialSecurityCode: doc.get("socialSecurityCode"),
            personalEmail: doc.get("personalEmail"),
            personalPhone: doc.get("personalPhone"),
            occupation: doc.get("occupation"),
            contactReason: doc.get("contactReason"),
            birthDateStr: "..." // <-- HERE
          }))
      )
    );
}

推荐阅读