簡體   English   中英

如何在 AngularFire2 的 Firestore 中檢索集合的文檔 ID

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

我已經瀏覽了 Angularfirestores 文檔,我覺得它沒有得到很好的記錄,所以我有這個問題需要解決,我試圖從我的 firestore 中獲取每個文檔的唯一 ID。 這是我的片段:

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

我在瀏覽器控制台中收到一條錯誤消息:

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)

我懷疑使用 data() 或其他問題存在問題。

在瀏覽了大量文檔、博客、教程和 stackoverflow 之后,我選擇了適合我的通用服務。 您所要做的就是指定一個路徑,然后您就可以訂閱生成的 Observable。

我將假設您有一個結構如下的組件:

  • myComponent(文件夾)

    • myComponent.component.ts

    • myComponent.module.ts

    • firestore.service.ts

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

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

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