【发布时间】:2018-10-06 15:17:17
【问题描述】:
我正在使用 AngularFire2 使用 Angular 5 和 Firestore 进行项目。我要做的是:“当用户在第一个输入中输入文档 ID 时,其他两个字段会通过从 Firebase 获取数据自动加载。
这是我的表单图片
这只是一个例子,如果所有数据都在一个集合中,这对我来说很容易,然后我只需将其预加载到 ngOnInit 中,但在某些情况下,我还必须显示来自其他集合的数据,例如 @ 987654324@.
这是我正在做的事情:
- 我检测到变化并调用函数
(change)="getPropertyInfo($event)" - 我调用 firebase 并获取数据
代码:
getPropertyInfo($document_id) {
this.afs.collection('properties', ref => {
return ref.where('strata_plan_no', '==', $document_id.target.value);
}).valueChanges().subscribe(property => {
if (property[0]) { // if these is any record
this.jobForm.street_address = property[0]['street_address'];
this.jobForm.suburb = property[0]['suburb'];
console.log(property[0]);
// I have a field called user_id in this property collection as well.
}
});
}
现在我还想使用选中的property_id 获取用户信息,我正在这样做:
getUserByID(id: string): Observable < any > {
return this.afs.collection('users').doc(id).valueChanges();
}
这里的问题是这个用户是一个可观察的。我正在寻找某种方法将其转换为对象,以便我也可以将其绑定到表单中的用户字段。
另外,如果是用户,如果我像上面的代码一样订阅 observable,我将无法立即获取数据以显示,因为它是异步的。
如果我错了,请纠正我并提出一些我可以尝试的建议。
谢谢
更新
我听从了 DauleDK 的 建议。现在,我正在使用响应式表单方法来更多地了解我的表单处理,Watched Observable 系列,并且对事情的内部运作方式有了一个合理的了解。
这是我现在拥有的:
ngAfterViewInit(): void {
this.jobsForm.get('property.strata_plan_no')
.valueChanges
.sample(Observable.fromEvent(this.strata_plan_no_input.nativeElement, 'blur'))
.subscribe((strata_plan_no) => {
this.propertyService.findByStrataPlanNo(strata_plan_no)
.filter((property) => property !== null) // filter nulls
.map(property => property[0]) // return the first element of the array
.subscribe((property) => {
console.log(property.manager_id); // this log gives me the ID i'm looking for.
this.managerService.findByID(property.manager_id).subscribe((manager) => { // this subscribe gives me an error
console.log(manager);
});
});
});
}
这是我得到的错误:
core.js:1449 ERROR TypeError: Cannot read property 'onSnapshot' of undefined
at Observable.eval [as _subscribe] (fromRef.js:8)
at Observable._trySubscribe (Observable.js:172)
at Observable.subscribe (Observable.js:160)
at ObserveOnOperator.call (observeOn.js:74)
at Observable.subscribe (Observable.js:157)
at Observable.ConnectableObservable.connect (ConnectableObservable.js:43)
at RefCountOperator.call (refCount.js:25)
at Observable.subscribe (Observable.js:157)
at MapOperator.call (map.js:57)
at Observable.subscribe (Observable.js:157)
【问题讨论】:
标签: angular firebase angular5 google-cloud-firestore angular2-observables