【发布时间】:2019-08-27 20:20:37
【问题描述】:
我正在使用 Angular 和 Firebase 开展一个小项目。当日期更改时,我需要获取在该日期或之前创建的“问题”列表以及当天该问题的单个“答案”。
当前日期是一个 BehaviorSubject,所以当它发生变化时,我使用 switchmap 来获取该日期的问题和答案列表。
但似乎在使用 forkJoin 和 map 将两个数组组合/合并为一个之后,我的页面上没有显示任何内容。但是,如果我只是在 forkJoin 之前返回 QuestionsCollection,我会得到问题列表,但这无济于事,因为在该日期我仍然没有该问题的答案。
所以在 forkJoin 将导致之前只返回 const q。 如下所示的问题列表(该 answer 属性是默认值,因为如果我没有来自数据库的问题,我会为用户实例化一个新问题,一旦他们保存分数就会添加该问题),但使用 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(),
})
})
})
);
}
【问题讨论】:
标签: angular typescript firebase rxjs google-cloud-firestore