使用 AngularFire 处理 firestore 集合中的 snapshotChanges

handle snapshotChanges in firestore collection using AngularFire

我 运行 我的应用程序与

完美搭配
"@angular/fire": "^6.1.5",
"@angular/core": "~12.0.2"

就像

Service.ts

getInboxCollection(userId: string) {
 return this.firestore.collection(`/user/${userId}/inbox/`).snapshotChanges().pipe(
       map(
         changes => {
           return changes.map(
             a => {
              const data: any = a.payload.doc.data();
              data.id = a.payload.doc['id'];
              return data;
            });
        })
    );
}

Component.ts

this.service.getInboxCollection(this.userId).subscribe((res: any) => {
    console.log(res);
}

现在我已经转移到最新版本的 AngularFire,即

"@angular/fire": "^7.0.4",

新的变化是

service.ts

import { doc as fireDoc, docData, Firestore, docSnapshots } from '@angular/fire/firestore';

getInboxCollection(userId: string) {
 const refOfInbox = fireCollection(this.firestore, `/user/${userId}/inbox/`);
    return docSnapshots(fireDoc(refOfInbox)).pipe(map(res => {
      const data = res.data();
        data['id'] = res.id;
        return data;
    }))
}

Component.ts

this.service.getInboxCollection(this.userId).subscribe((res: any) => {
    console.log(res);
}

但我在控制台上未定义。
根据此官方文档 docSnapshots 数据仅可通过访问 firebasse 文档 获得。
https://github.com/angular/angularfire/blob/master/docs/version-7-upgrade.md

但是如何使用 docSnapshots 或其他实时更改的方法从 firebase 集合 获取数据?
请帮助我更好的方法。
提前致谢。

我已经按照您习惯使用的方式将您的代码重构为 return 数据 angular/fire 7. 就像在单个文档上使用 docSnapshots 一样,您可以使用 collectionChanges 在集合上。请确保您的路径正确,否则数据将不会被 returned。

服务:

import {collection, collectionSnapshots, doc, docSnapshots, Firestore} from '@angular/fire/firestore';


  getInboxCollection(userId: string) {
    const refOfInbox = collection(this.firestore, `/user/${userId}/inbox/`);
    return collectionSnapshots(refOfInbox).pipe(map(res => res.map(data => {
      const id = data.id
      const docData = data.data()
      return {...docData, id}
    })));

组件:

    this.service.getInboxCollection(this.userId).subscribe((res: any) => {
      console.log(res);
    });