mohammadalha
mohammadalha

Reputation: 19

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

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

Upvotes: 0

Views: 1596

Answers (1)

DbC
DbC

Reputation: 86

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.

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

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.

Upvotes: 3

Related Questions