【发布时间】:2021-08-23 20:05:07
【问题描述】:
我正在尝试将带有 DocumentReferences 的 Object 的 Observable 转换为我的整个 Object 的 Observable。
我的 Firestore 查询返回 QuestDocument 的 Observable,如下所示(去除原始类型):
export interface QuestDocument {
...
owner: DocumentReference<User>;
...
collaborators?: DocumentReference<User>[];
categories?: DocumentReference<Category>[];
}
在我的转换器中,我可以调用其他 Firestore 服务来检索 DocumentReferences 到 User 和 Category 的值(扁平结构,所以这里没有问题)。
我的目标是创建一个 Quest 类型的 Observable,但我的嵌套 Observable 没有被正确解析。
export interface Quest {
...
owner: User;
...
collaborators?: User[];
categories?: Category[];
}
这是我目前所拥有的:
doc$(docId: string): Observable<Quest> {
return this.doc(docId).valueChanges()
.pipe(
mergeMap(questDoc => {
const owner$ = this.userService.doc$(questDoc.owner.id);
const collaborators$ = forkJoin(questDoc.collaborators.map(
(userRef: DocumentReference) => {
return this.userService.doc$(userRef.id)
}
));
const categories$ = forkJoin(questDoc.categories.map(
(categoryRef: DocumentReference) => this.categoryService.doc$(categoryRef.id)
));
const joined = forkJoin({
owner: owner$,
collaborators: collaborators$,
categories: categories$
});
joined.subscribe(data => console.log(data));
return joined.pipe(
map(value => {
return Object.defineProperties(questDoc, {
qid: { value: docId },
owner: { value: value.owner },
collaborators: { value: value.collaborators },
categories: { value: value.categories }
}) as Quest;
})
)
})
);
}
所有类型都匹配,我应该收到一个Observable<Quest>,但是当我尝试打印该值时,它返回undefined,而第二个.pipe() 永远不会到达。
【问题讨论】:
-
forkJoin只会在所有源 observables 都发射并完成后发射。对categoryService.doc$()和userService.doc$()的调用会返回完整的可观察对象吗?如果没有,您可以将.pipe(first())添加到您的joinedforkJoin 中的 3 个来源中的每一个。 -
我不确定 completion 在 Observable 方面的含义,因为我对这些概念还很陌生。两个服务的
.doc$()调用返回各自类文档类型的Observables(参见QuestDocument),映射到实现的类型(仅将文档的ID 添加到Category和User)。检索类文档类型的底层函数是 AngularFire 的 Firestore SDK 的扩展。
标签: angular typescript google-cloud-firestore rxjs angularfire2