gpt4 book ai didi

angular - 如何将两个 firebase 集合组合成一个新的对象数组

转载 作者:搜寻专家 更新时间:2023-10-30 21:45:39 24 4
gpt4 key购买 nike

我正在使用 Angular 和 Firebase 开发一个小项目。当日期更改时,我需要获取在该日期当天或之前创建的“问题”列表,以及当天该问题的单个“答案”。

当前日期是一个 BehaviorSubject,所以当它发生变化时,我使用一个切换图来获取该日期的问题和答案列表。

但似乎在使用 forkJoin 和 map 将两个数组合并/合并为一个数组后,我的页面上没有显示任何内容。但是,如果我在 forkJoin 之前简单地返回 QuestionsCollection,我会得到问题列表,但这无济于事,因为在那个日期我仍然没有那个问题的答案。

所以只返回 const q,在 forkJoin 之前会产生。如下所示的问题列表(该答案属性是默认值,因为如果我没有来自数据库的问题,我会为用户实例化一个新的,一旦他们保存他们的分数就会添加),但是使用 forkJoin,甚至不返回 []

[
{
"id": "e0gdRmeNu2bheekeyT6m",
"uid": "uPhcLZkaRYRXpsSZC0zbRqUOWOq2",
"question": "Combine Q with A",
"goal": 10,
"answer": {
"id": null,
"score": null,
"qid": null,
},
...
]

在 firebase 中,答案和问题是单独的集合,因为用户每天只会有 1 个答案,我不想在询问某个日期的问题时得到所有以前的答案。

主要方法

getQuestions() {
//Observable<Question[]>
this.questions = this.dateService.dateStore
.pipe(
switchMap(date => {
const startDate = moment(date).startOf('day').utc().toDate();
const endDate = moment(date).endOf('day').utc().toDate();

//Observable<Question[]>
const q = this.getQuestionsUntilDate(endDate);
//Observable<Answer[]>
const a = this.getAnswersForDateRange(startDate, endDate);

//forkjoin and map results together?
//doesn't seem to work
return forkJoin([q, a])
.pipe(
map(val => {
let questions = val[0];
let answers = val[1];

questions.forEach(question => {
//a answer is not guaranteed to exist so only
//add it to the question if we found one.
const answer = answers.find(answer => answer.qid === question.id);
if (answer) {
question.answer = answer;
}
});

return questions;
}));
}))
}

问答征集电话

    private getQuestionsUntilDate(date: Date) {
return this.qCollection(ref => ref
.where('timestamp', '<=', date)
.where('uid', '==', this.auth.userId)
.orderBy('timestamp'))
.snapshotChanges()
.pipe(
map(res => {
return res.map(q => {
return new Question({
id: q.payload.doc.id,
...q.payload.doc.data()
})
})
})
);
}

private getAnswersForDateRange(sDate: Date, eDate: Date) {
return this.aCollection(ref => ref
.where('timestamp', '<=', eDate)
.where('timestamp', '>=', sDate)
.where('uid', '==', this.auth.userId))
.snapshotChanges()
.pipe(
map(res => {
return res.map(a => {
return new Answer({
id: a.payload.doc.id,
...a.payload.doc.data(),
})
})
})
);
}

最佳答案

forkJoin 将在所有这些可观察对象完成时发出给定可观察对象的最后一个值。

forkJoin marble diagram

似乎 snapshotChanges() 返回一个 Observable,它不会以发出第一个值完成。

所以尝试用 forkJoin 代替用zip ,例如。

zip 可让您按发射顺序组合来自可观察对象的值:第一个值与第一个值,第二个与第二个,等等。

如果你需要对来自任何流的更新使用react——试试combineLatest .

注意:您需要从 rxjs 导入 zip,不是 rxjs/operators

关于angular - 如何将两个 firebase 集合组合成一个新的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55543692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com