简体   繁体   English

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

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

I'm trying to get collection data from a firestore instance and don't want to use valueChanges{idField: id}.我正在尝试从 firestore 实例获取集合数据,并且不想使用 valueChanges {idField:id}。 So far this is the only solution that somehow processes some of the data and gets the output close to what I need.到目前为止,这是唯一能以某种方式处理一些数据并使输出接近我需要的解决方案。

I'm new to angular & angular/fire as well as to rxjs and am really struggling to understand observables, pipe, map and rxjs in general.我是 angular & angular/fire 以及 rxjs 的新手,我真的很难理解 observables、pipe、map 和 rxjs。

What am I missing here?我在这里想念什么?

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;
      })
    )
  );
}

This should work.这应该有效。

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
      })
     )
   )
}

which is equivalent to:这相当于:

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

Since you only need to fetch the Job's data, collectionData() is way more appropriate .由于您只需要获取 Job 的数据,因此collectionData()更合适

collectionSnapshots() may be interesting when you need to perform additional operations on each Job, such as updating/deleting each one of them, which is possible with snapshot.ref当您需要对每个 Job 执行额外操作时, collectionSnapshots()可能会很有趣,例如更新/删除它们中的每一个,这可以通过snapshot.ref

Example:例子:

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

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

This is a mere example and the logic may not apply to your use case.这只是一个示例,逻辑可能不适用于您的用例。

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

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