简体   繁体   English

如何在 AngularFire2 的 Firestore 中检索集合的文档 ID

[英]How to retrieve document id's for collections in AngularFire2's Firestore

I have been through the Angularfirestores documentation which to me i feel isnt well documented, so i have this issue which i need to solve, i am trying to fetch the unique ids for each document from my firestore.我已经浏览了 Angularfirestores 文档,我觉得它没有得到很好的记录,所以我有这个问题需要解决,我试图从我的 firestore 中获取每个文档的唯一 ID。 Here is my snippet:这是我的片段:

private businessCollection2: AngularFirestoreCollection<Ibusiness>;
businesses2: Observable<any>;

this.businessCollection2 = this.fb.collection('businesses');
this.businesses2 = this.businessCollection2.snapshotChanges();

this.businesses2.pipe(
       map(
         changes => {
       const data = changes.payload.data();
       const id = changes.payload.id;
       return {id, ...data};
    })).subscribe(changes => {
      console.log(changes.id);
    });

i get an error in my browser console that says:我在浏览器控制台中收到一条错误消息:

ERROR TypeError: Cannot read property 'data' of undefined
    at MapSubscriber.eval [as project] (app.component.ts:63)
    at MapSubscriber._next (map.js:35)
    at MapSubscriber.Subscriber.next (Subscriber.js:54)
    at eval (angularfire2.js:36)
    at ZoneDelegate.invoke (zone.js:388)
    at Object.onInvoke (core.js:4760)
    at ZoneDelegate.invoke (zone.js:387)
    at Zone.run (zone.js:138)
    at NgZone.run (core.js:4577)
    at SafeSubscriber.eval [as _next] (angularfire2.js:36)

i am suspecting there's either an issue with using data(), or something else.我怀疑使用 data() 或其他问题存在问题。

After jumping between a lot of the documentation, blogs, tutorials and stackoverflow I've settled on a generic service that works for me.在浏览了大量文档、博客、教程和 stackoverflow 之后,我选择了适合我的通用服务。 All you have to do is specify a path and then you can subscribe to the resulting Observable.您所要做的就是指定一个路径,然后您就可以订阅生成的 Observable。

I'm going to assume that you've got a component structured like this:我将假设您有一个结构如下的组件:

  • myComponent (folder) myComponent(文件夹)

    • myComponent.component.ts myComponent.component.ts

    • myComponent.module.ts myComponent.module.ts

    • firestore.service.ts firestore.service.ts

firestore.service.ts (this is a long one.) firestore.service.ts (这是一个很长的。)

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, 
AngularFirestoreDocument } from '@angular/fire/firestore';
import { FirebaseError } from 'firebase';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
   export class FirestoreService { 

   constructor(
    private db: AngularFirestore
   ) {

   }


 getCollectionRef(path: string, sortBy?: string): 
  AngularFirestoreCollection {
    if (sortBy === undefined) {
      return this.db.collection(path);
    } else {
      return this.db.collection(path, ref => ref.orderBy(sortBy));
    }
  }

  getDocumentRef(path: string): AngularFirestoreDocument {
    return this.db.doc(path);
  }

  getCollectionSnapshot(
    path: string,
    sortBy?: string
  ): Observable<any[]> {
    return this.getCollectionRef(path, sortBy).snapshotChanges();
  }

   getDocumentSnapshot(
    path: string,
  ): Observable<any> {
    return this.getDocumentRef(path).snapshotChanges();
  }

  getCollectionValue(
    path: string,
    sortBy?: string
  ): Observable<any[]> {
    return this.getCollectionRef(path, sortBy).valueChanges();
  }

  getDocumentValue(
    path: string,
  ): Observable<any> {
    return this.getDocumentRef(path).valueChanges();
  }

  getDocument(path: string): Observable<any> {
    return this.getDocumentSnapshot(path).pipe(
      map(changes => {
        const data = changes.payload.data();
        const id = changes.payload.id;
        return { id, ...data };
      })
    );
  }

  getCollection(path: string, sortBy?: string): Observable<any[]> {
    return this.getCollectionSnapshot(path, sortBy).pipe(
      map(changes => {
        return changes.map(change => {
          const data = change.payload.doc.data();
          const id = change.payload.doc.id;
          return { id, ...data };
        });
      }
      ));

  }

  createDocument(path: string, data: object):
  Promise<any | FirebaseError> {
    return this.getDocumentRef(path).set(data)
    .then(() => {
      return null;
    })
    .catch((error: FirebaseError) => {
      return error;
    });
  }

  updateDocument(path: string, data: object):
  Promise<any | FirebaseError> {
    return this.getDocumentRef(path).update(data)
    .then(() => {
      return null;
    })
    .catch((error: FirebaseError) => {
      return error;
    });
  }

  deleteDocument(path: string):
   Promise<any | FirebaseError> {
    return this.getDocumentRef(path).delete()
    .then(() => {
      return null;
    })
    .catch((error: FirebaseError) => {
      return error;
    });
  }

  createCollectionItem(path: string, data: object):
   Promise<any | FirebaseError> {
    return this.getCollectionRef(path).add(data)
    .then(() => {
      return null;
    })
    .catch((error: FirebaseError) => {
      return error;
    });
  }


 }

myComponent.module.ts myComponent.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FirestoreService } from './firestore.service';
import { MyComponent } from './myComponent.component';


@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [MyComponent],
  providers: [
   FirestoreService,
  ]
})
export class MyComponentModule { }

myComponent.component.ts myComponent.component.ts

import { Component, OnInit } from '@angular/core';
import { FirestoreService } from './firestore.service';
import { User } from 'firebase/app';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-myComponent', // remember to change prefix 'app' to the one that your app uses.
  templateUrl: './myComponent.component.html',
  styleUrls: ['./myComponent.component.css']
})
  export class MyComponentComponent implements OnInit {
    firestoreData: Observable<any[]>;
    dataPath = 'path/';

  constructor(
    private firestore: FirestoreService
  ) {

  }

  ngOnInit() {

  this.firestoreData = this.firestore.getCollection(this.dataPath);

    this.firestoreData.subscribe(firestoreData => {
      console.log(firestoreData);
      console.log(firestoreData[0].id);
      // in the template you can use *ngFor="let business of businesses | async"
    } );

  }
}

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

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