【发布时间】:2020-03-19 04:24:42
【问题描述】:
如何构建仅限于单个文档的 Observable?
这会在查询任意数量的文档时构建一个 Observable:
foo.component.ts
import { AngularFirestore } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
...
export class FooComponent implements OnInit {
...
docs: Observable<any[]>;
constructor(private db: AngularFirestore) {
this.docs = db.collection('myCollection', ref => ref.where('name', '==', 'foobar')).valueChanges();
}
foo.component.html
<div *ngFor="let doc of docs | async">
{{ doc.name }}, {{ doc.address }}
</div>
当我知道只有 1 个文档会被退回时,我该怎么做?我只是不会提前知道文档 ID。
类似于上面的代码,除了只有doc: Observable<any>; 而不是docs: Observable<any[]>;,所以我不必对结果使用*ngFor 循环?
我试过了
this.doc = db.collection('myCollection', ref => ref.where('name', '==', 'foobar').limit(1)).valueChanges();
【问题讨论】:
-
添加了“import { take } from 'rxjs/operators';”但它没有给出查询中的 1 个文档 :(
-
stackoverflow.com/questions/46654670/… 请参阅此内容以供参考。你必须导入
import { take } from 'rxjs/operators'; -
你得到了什么?
-
对象 "docs: Observable
" 工作正常,但 "doc: Observable " 没有任何价值.. 甚至没有错误 -
如果添加
.subscribe(res => console.log('response', res));会怎样?
标签: angular typescript firebase angularfire2 angularfire