繁体   English   中英

使用 angular/fire/rxjs 从 Firestore 检索数据

[英]Retrieving Data from Firestore with angular/fire/rxjs

我正在尝试从 firestore 实例获取集合数据,并且不想使用 valueChanges {idField:id}。 到目前为止,这是唯一能以某种方式处理一些数据并使输出接近我需要的解决方案。

我是 angular & angular/fire 以及 rxjs 的新手,我真的很难理解 observables、pipe、map 和 rxjs。

我在这里想念什么?

async fetchJobs() {
  let jc = await collection(this.firestore, 'jobs');
  let cSN = await collectionSnapshots(jc);
  let jobsArr = cSN.pipe(
    map((data) =>
      data.forEach((d) => {
        let jobsData = d['_document']['data']['value']['mapValue'][
          'fields'
        ] as Job;
        const newData = {
          id: d.id,
          title: jobsData.title,
          subtitle: jobsData.subtitle,
          description: jobsData.description,
          publish: jobsData.publish,
          img: jobsData.img,
        } as Job;
        return newData;
      })
    )
  );
}

这应该有效。

fetchJobs(): Observable<Job[]> {
   const jc = collection(this.firestore, 'jobs')
   return collectionSnapshots(jc)
   .pipe(
     map((snapshots) =>
      snapshots.map((snapshot) => {
        return { ...snapshot.data(), id: snapshot.id } as Job
      })
     )
   )
}

这相当于:

fetchJobs(): Observable<Job[]> {
   const jc = collection(this.firestore, 'jobs')
   return collectionData(jc, { idField: 'id' })
   .pipe(
     map((data) => data as Job[])
   )
}

由于您只需要获取 Job 的数据,因此collectionData()更合适

当您需要对每个 Job 执行额外操作时, collectionSnapshots()可能会很有趣,例如更新/删除它们中的每一个,这可以通过snapshot.ref

例子:

fetchJobs() {
   const jc = collection(this.firestore, 'jobs')
   return collectionSnapshots(jc)
}

deleteAllJobs() {
   fetchJobs()
   .pipe(take(1))
   .subscribe(snapshots =>
      snapshots.map((snapshot) => {
        deleteDoc(snapshot.ref)
      })
   )
}

这只是一个示例,逻辑可能不适用于您的用例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM