我有查询 Firestore 并返回 Observable 类型的工作代码ImageUploadWId[]
。我想退货Promise
反而。这是因为
- 我的数据不经常变化;
- 我正在根据传入的数据执行删除。
SnapshotChanges()
返回操作数组。第一个操作包含大小为 1 的不完整数组。最后一个操作包含大小为 4 的数组。最后一个数组是完整的;它拥有所有ImageUploadWIds
从一groupId
.
我只想要一个数组ImageUploadWIds
仅来自指定的 groupId。使用 Promise 给了我ImageUploadWIds
从所有的groupIds
。我相信 where 子句不起作用。
这是我的工作代码,仅打印imageUpload
groupIds 来自一个 groupId,但返回多个数组。最后一个数组是我唯一需要的。编辑(添加日志语句):
getImageInfosWIds(bathroomGroupId: string): Observable<ImageUploadWId[]> {
return this.afs.collection(this.bathroomImagesLocation,
ref => ref.where('groupId', '==', bathroomGroupId)).snapshotChanges()
.map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
const imageUpload = new ImageUploadWId();
imageUpload.set(id, <ImageUpload>data);
return imageUpload;
})
})
}
onDeleteGroup(groupId: string) {
this.bathroomGroupService.getImageInfosWIds(groupId)
.subscribe((imageUploads) => {
console.log("imageUploads.length: " + imageUploads.length);
for (let imageUpload of imageUploads) {
console.log("(groupId, filename): (" + imageUpload.groupId + ", " + imageUpload.filename + ")");
}
})
}
这是我尝试使用 Promise 的代码。这会打印来自我的两个组的 imageUploads,而不是仅打印给定的 BathroomGroupId。
getImageInfosWIds(bathroomGroupId: string): Promise<QuerySnapshot> {
return this.afs.collection(this.bathroomImagesLocation,
ref => ref.where("groupId", "==", bathroomGroupId))
.ref
.get();
}
onDeleteGroup(groupId: string) {
this.bathroomGroupService.getImageInfosWIds(groupId)
.then( (querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log("edit-bathrooms: " + doc.data().groupId);
})
},
() => {console.log("Error in edit-bathrooms. promise unfullfilled " +
"in onDeleteGroup( " + groupId + " )")});
}
编辑:这是最终有效的代码:
onDeleteGroup(groupId: string) {
this.bathroomGroupService.getImageInfosWIdsObservable(groupId)
.pipe(take(1)).subscribe(
data => {
console.log(data[0].groupId);
});
}
getImageInfosWIdsObservable(bathroomGroupId: string) {
return this.afs.collection(this.bathroomImagesLocation,
ref => ref.where('groupId', '==', bathroomGroupId)).snapshotChanges() //rxjs 5 -> 6 library
.pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data();
const documentId = a.payload.doc.id;
const imageUpload = new ImageUploadWId();
imageUpload.set(documentId, <ImageUpload>data);
return imageUpload;
}))
);
}
最后一句话。如果您仍然获得额外的数组,则您可能已在代码的另一部分订阅了相同的 Firestore 集合并且未取消订阅。这是我的问题的一部分。