【问题标题】:How to get one field of every document of a collection on Firestore?如何在 Firestore 上获取集合的每个文档的一个字段?
【发布时间】:2019-11-17 16:49:21
【问题描述】:

我正在尝试获取一个集合的每个文档的 一个 字段。我正在做的是做一个订阅方法来填充一个动态过滤器的列表,但我知道它不起作用,什么是得到我想要的最好的方法?我想订阅它,这是我的代码:

this.af.collection('objects').valueChanges().subscribe(data => {        
  this.listTitles.push(data.title)
});

【问题讨论】:

  • 最后我修复了它,我唯一要做的就是订阅所有数据,然后只显示在过滤标题的列表中,我也在使用辅助数组让它工作

标签: angular google-cloud-firestore ionic4


【解决方案1】:

只需映射结果并在模板中使用异步

class YourComponent{
  listTitles:Observable<String>;

  constructor(){
    this.listTitles = this.af.collection('objects').valueChanges().pipe(
      map(objs => objs.map(obj => obj.title))
    )
  }
}

在你的模板中:

<ng-container *ngFor="let item of listTitles | async">
 <!-- have fun -->
</ng-container>

【讨论】:

  • 对不起,我忘了说 ionic4
  • 我认为它应该仍然可以工作。我以为您使用的是 angularfire2?
  • 您好,它不起作用,obj.title 说“属性 'title' 在类型 'unknown[]'.ts(2339) 上不存在”
  • 是的,我的错,observable 发出了所有的值,我要编辑我的第一篇文章
  • obj.title doesn't exist on unknow :(
【解决方案2】:

.subscribe 在您的情况下不起作用,可能您需要像这样拆分代码,

this.objectCollectionRef = this.af.collection('objects');
this.objectCollection = this.objectCollectionRef.valueChanges();


for(let data of this.objectCollection){
   this.listTitles.push(data.title)
}

希望这会有所帮助!

【讨论】:

  • this.objectCollection 是否包含任何数据(或)它将为空?
  • 当您将listTitles 插入为{{listTitles}} 并显示在您的html 中时会发生什么?
  • Type 'Observable' 不是数组类型或字符串类型。ts(2495) (this objectCollection)....
猜你喜欢
  • 1970-01-01
  • 2021-01-23
  • 2021-08-06
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 2019-02-05
  • 2021-10-21
  • 1970-01-01
相关资源
最近更新 更多