AngularFire中获取集合文档时关联文档引用字段数据的问题
Resolving Reference Fields in AngularFire for
machine-site-map Documents Got it, let's fix this. Right now your method only pulls in the raw machine-site-map documents (with their IsActive check), but it doesn't resolve the machineRef and siteRef references to fetch the actual machine and site data. Here's how to combine AngularFire with RxJS operators to get all the linked data you need:
Step-by-Step Implementation
Modify your getActiveMachineSiteMap() method like this:
import { forkJoin } from 'rxjs'; import { switchMap, map } from 'rxjs/operators'; getActiveMachineSiteMap() { // 1. First fetch all active machine-site-map records (including document ID) return this.db.collection('machine-site-map', ref => ref.where('IsActive', '==', true)) .valueChanges({ idField: 'Id' }) .pipe( // 2. For each map document, resolve its linked machine and site references switchMap((machineSiteMaps) => { // Create an observable for each map that fetches its associated data const resolvedMapObservables = machineSiteMaps.map(mapDoc => { // Fetch data from the machine reference const machineData$ = this.db.doc(mapDoc.machineRef).valueChanges(); // Fetch data from the site reference const siteData$ = this.db.doc(mapDoc.siteRef).valueChanges(); // Combine both requests and merge with the original map data return forkJoin([machineData$, siteData$]).pipe( map(([machine, site]) => ({ ...mapDoc, // Keep original map fields (Id, IsActive, refs) machine, // Add full machine data to the object site // Add full site data to the object })) ); }); // Combine all resolved map observables into a single array result return forkJoin(resolvedMapObservables); }) ); }
Key Details:
forkJoin: Used twice here—first to fetch machine and site data in parallel for a single map document, then to combine all fully resolved map objects into one array. It waits for all requests to complete before emitting results.switchMap: Takes the initial list of map documents and transforms it into a new stream that handles resolving all references.map: Merges the original map data with the fetched machine/site data, so you end up with a single object containing everything you need.
How to Use This in Your Component
When you subscribe to this method, you'll get an array of objects where each entry includes the original map data plus the full linked machine and site records:
this.yourService.getActiveMachineSiteMap().subscribe((fullData) => { console.log('Complete machine-site-map data:', fullData); // Each item has: Id, IsActive, machineRef, siteRef, machine, site });
Quick Notes:
- Ensure
machineRefandsiteRefare valid FirestoreDocumentReferenceobjects in your database. If they're stored as string paths instead, convert them to references first withthis.db.doc(mapDoc.machineRefPath).ref. - Add
catchErroroperators if you need to handle cases where a linked machine/site document no longer exists.
内容的提问来源于stack exchange,提问作者abinash mohapatra
相关产品推荐
相关产品推荐

