【问题标题】:handle snapshotChanges in firestore collection using AngularFire使用AngularFire处理firestore集合中的snapshotChanges
【发布时间】:2021-11-09 17:16:35
【问题描述】:

我已经完美地运行了我的应用程序

"@angular/fire": "^6.1.5",
"@angular/core": "~12.0.2"

就像

服务.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;
            });
        })
    );
}

组件.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;
    }))
}

组件.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 集合 获取数据?
请帮助我找到更好的方法。
提前致谢。

【问题讨论】:

    标签: javascript angular firebase google-cloud-firestore angularfire


    【解决方案1】:

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

    服务:

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

    【讨论】:

    • collectionChanges 只获取更改的文档,而不是像 snapshotChanges 那样获取整个集合。
    • @cakePHP 我更新了我的答案以使用collectionSnapshots,这将返回整个集合,如snapshotChanges
    猜你喜欢
    • 1970-01-01
    • 2018-06-19
    • 2018-10-09
    • 2021-01-23
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 2019-10-03
    • 2019-11-24
    相关资源
    最近更新 更多