【问题标题】:How to get ID of collection in Firestore with angular Firestore如何使用 Angular Firestore 获取 Firestore 中的集合 ID
【发布时间】:2021-05-26 17:59:38
【问题描述】:

当我以这种方式查询 Firestore 数据库时,我无法获取文档的 ID:

你能给我一些帮助吗?

import { Component, OnInit } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection  } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
export interface Item { name: string; }

@Component({
  selector: 'app-annonces-contactees',
  templateUrl: './annonces-contactees.page.html',
  styleUrls: ['./annonces-contactees.page.scss'],
})
export class AnnoncesContacteesPage implements OnInit {
  private annoncesCollection: AngularFirestoreCollection<Item>;
  annonces: Observable<Item[]>;
    constructor(private afs: AngularFirestore) {
      this.annoncesCollection = afs.collection('annonces', ref => ref.where('prix', '>=', 1000000))
      this.annonces = this.annoncesCollection.valueChanges();
   }

  ngOnInit() {
}

}

【问题讨论】:

  • 试试这个.. this.annoncesCollection..snapshotChanges().pipe( map(actions => actions.map(a => { const data = a.payload.doc.data() as Item ; const id = a.payload.doc.id; return { id, ...data }; }))
  • 谢谢,但是如何在我的 html 代码中显示它?现在我用它来获得结果:
  • {{ annonce.prix }}
  • 你确定你的代码吗?我收到错误
  • 标签: javascript ionic-framework google-cloud-firestore angularfire2


    【解决方案1】:

    我将举一个例子来说明我是如何添加它的: 假设我有医院的集合,每个医院都有自己的名称、电话和位置。

      constructor(private firestore:AngularFirestore){}
      hospitalsArray=[];
      ngOnInit(){
          this.firestore.collection("hospitals").snapshotChanges().subscribe((data) => {
            this.hospitalsArray = data.map(e => {
              return { id: e.payload.doc.id, location: e.payload.doc.data()["location"], number: e.payload.doc.data()["phone"], name: e.payload.doc.data()["name"]}
            })
      }
    

    “hospitals”是集合的名称,这个id是文档的id。

    所以如果要在html文件中显示

    <ion-item *ngFor="let hospital of hospitalsArray">
    <ion-label>{{hospital.name}}</ion-label>
    </ion-item>
    

    【讨论】:

    • 您好,您知道如何按 ID 对数据进行排序吗?当我不使用 where 条件时,我得到按 ID 排序的结果,但结果是随机排序的,因为 Where 条件.. 知道吗?
    • 其实我没试过,不知道有没有内置函数用于数组排序,如果没有的话可以尝试使用一些排序算法。我也将尝试搜索它。
    • 但是为什么要按 id 对数组进行排序呢??
    • 我需要对数组购买日期进行排序,但由于我使用的是“Where”,因此不允许使用其他字段(“date”)对数据进行排序。所以我尝试直接按模板中的 ID 或日期对数据进行排序。感谢您的宝贵时间。
    • 你可以在填充你用来填充数据的数组之后。根据您想要的字段对其进行排序。无论如何,“您在哪里使用”是什么意思??
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签