【问题标题】:get the ID of collection document from Firestore using Angularfire2 in ionic 3 [duplicate]使用 ionic 3 中的 Angularfire2 从 Firestore 获取集合文档的 ID [重复]
【发布时间】:2019-04-09 16:08:34
【问题描述】:

我正在尝试获取集合的 ID 以在离子页面中使用它:

这是我的界面:

  export interface Item { 
  categoryOfPost: string; 
  imageUrl: string;
  nameOfPost: string;
  cityOfPost: string;
  createdDate: string;
  currencyOfPost: string;
  priceOfPost: number;
  typeOfPost: number;
  statusOfPost: string;
  id?: string;
}

 private itemsCollection: AngularFirestoreCollection<Item>;
  items: Observable<Item[]>;

这是getPosts函数的内容

  this.itemsCollection = this.afs.collection('posts', ref => ref.orderBy('createdDate', 'desc'));
  this.items = this.itemsCollection.valueChanges(); 

当我想查看我使用的内容时:

 <ion-card style="margin-bottom: 25px; background-color: burlywood" *ngFor="let item of items | async">
    <ion-item text-wrap  style="margin-bottom: 25px; background-color: burlywood"> 
        <ion-list >       
          <ion-item> 
            <img src="{{ item.imageUrl }}">            
            cityOfPost: {{ item.id }}            
          <button ion-button (click)="detailpage(item.id)">click to test  </button>
          </ion-item>           
        </ion-list>  
    </ion-item>
  </ion-card>  

我可以在 HTML 上显示除未定义的 ID 之外的所有内容 ???? 正确的显示方式是什么???

谢谢。

【问题讨论】:

  • 为这个基本问题创建了一个函数。它位于bottom of this page。不知道为什么这不是 AngularFire2 的一部分...

标签: typescript firebase google-cloud-firestore angularfire2


【解决方案1】:

这是因为使用valueChanges()“所有快照元数据都被剥离,只是方法只提供数据”,如doc中所述。

您应该使用snapshotChanges(),请参阅文档here,其中说:“为什么要使用它?- 当您需要数据列表但又想保留元数据时。”

【讨论】:

    【解决方案2】:

    我把代码改成:

      this.itemsCollection = this.afs.collection('posts', ref => ref.orderBy('createdDate', 'desc'));
      this.items = this.itemsCollection.snapshotChanges().pipe(
        map(actions => actions.map(a => {
          const data = a.payload.doc.data() as Item;
          const id = a.payload.doc.id;
          return { id, ...data };
        }))
      );
    

    而且效果很好。

    【讨论】:

      猜你喜欢
      • 2018-04-04
      • 2019-09-17
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 2019-09-24
      相关资源
      最近更新 更多