【问题标题】:Angular Firestore Valuechanges get document referenceAngular Firestore Valuechanges 获取文档参考
【发布时间】:2021-02-23 18:39:08
【问题描述】:

我正在使用 Angular 和 google cloud firestore 来加载数据。 我也有一个模型类,我们就叫它IMyModel

export interface IMyModel{
    data: any;
    id: string;
}

其中id 是firestore 上文档的id。我可以很容易地通过

var docs = this.firestore.collection('myCollection').valueChanges({ idField: 'id' }) as Observable<IMyModel[]>;这很好用。

但是现在,我也想要这个功能与文档参考。假设我改变了模型

export interface IMyModel{
    data: any;
    documentReference: DocumentReference;
}

我现在如何插入documentReference 字段?我已经试过了

var docs = this.firestore.collection('myCollection').valueChanges({ ref: 'documentReference', }) as Observable<IMyModel[]>;

但这不会插入字段。

【问题讨论】:

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


    【解决方案1】:

    valueChanges() 给你一个 observable。您可以通过.pipe(map(items => items.map(item => yourFunction(item)))) 将数据转换为您喜欢的:

    interface IMyModel {
      data: any;
      ref: DocumentReference;
    }
    const myCollection = this.firestore.collection<{ data: any }>('myCollection');
    const itemsWithId$ = myCollection.valueChanges({ idField: 'id' });
    const itemsWithRef$: Observable<IMyModel[]> = itemsWithId$.pipe(
      map(itemsWithId => {
        return itemsWithId.map(item => {
          return {
            data: item.data,
            ref: myCollection.doc(item.id).ref,
          };
        });
      }),
    );
    

    【讨论】:

    • 当然yourFunction 不需要是命名函数。您可以用内联代码替换它(在花括号中,只需构建并返回您需要的对象类型)。第一个 map 是一个 rxjs 运算符(从 'rxjs/operators' 导入),它将每条数据“映射”成新数据。第二个map 是数组的“内置”方法,将每个项目“映射”到一个新项目。
    【解决方案2】:

    你能试试这个解决方案吗?

    export interface Item { id: string; name: string; }
    @Component({
      selector: 'app-root',
      template: `
        <ul>
          <li *ngFor="let item of items | async">
            {{ item.name }}
          </li>
        </ul>
      `
    })
    export class AppComponent {
      private itemsCollection: AngularFirestoreCollection<Item>;
      items: Observable<Item[]>;
      constructor(private readonly afs: AngularFirestore) {
        this.itemsCollection = afs.collection<Item>('items');
        // .valueChanges() is simple. It just returns the 
        // JSON data without metadata. If you need the 
        // doc.id() in the value you must persist it your self
        // or use .snapshotChanges() instead. See the addItem()
        // method below for how to persist the id with
        // valueChanges()
        this.items = this.itemsCollection.valueChanges();
      }
    }
    

    更多参考请参考this链接。

    【讨论】:

      猜你喜欢
      • 2018-08-02
      • 2018-06-16
      • 2018-09-26
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      相关资源
      最近更新 更多