因此,通知集合中存储了一个通知对象列表,我的目标是检索早于当前日期时间的所有通知。
所以我的基本查询是:
return this.db.collection(environment.collection, ref => ref.where('staffRole', '==', staffRole).where('notificationDate', '<=', new Date().getTime()).orderBy('notificationDate', 'desc'))
.snapshotChanges()
.pipe(map(snaps => {
return snaps.map(snap => {
return <Notification>{
id: snap.payload.doc.id,
...Object.assign({}, snap.payload.doc.data())
}
});
}));
但是 new Date().getTime()
作为固定参数传递,而不是像我预期的那样实时传递。为了克服这个问题,我更改了订阅部分:
interval(1000)
.pipe(
map(tick => new Date()),
share()
).subscribe(date => {
// console.log(date.getTime());
this.notificationSubscriber !== undefined ? this.notificationSubscriber.unsubscribe() : false;
this.notificationSubscriber = this.notificationService.getNotifications(getStaffRolevalue(this.staffRole),
(this.staffRole === 'csa' || 'ops' || 'admin' ? null : this.loggedInStaffId)).subscribe(notifications => {
this.notifications = notifications;
const x = this.notificationCount;
this.notificationCount = notifications.filter(notification => notification.isRead === 0).length;
const y = this.notificationCount;
(y - x) === 1? this.playAudio() : false;
});
});
我的逻辑是每秒重新订阅可观察的内容。它确实有效,但读取文档的数据库使用量猛增。所以基本上这个逻辑也不能用。
有没有其他方法可以实现我想要的目标。我愿意接受任何建议,即使是关于更改我的界面,只要我实时检索通知即可。
界面:
export interface Notification {
id: string,
isRead: number,
jobNo: number,
notificationDate: number,
notificationMessage: string,
notificationTitle: string,
notificationType: number,
receiverId: string,
staffRole: number
}
最佳答案
我将服务中的查询更改为简单查询:
return this.db.collection(environment.collection, ref => ref.where('receiverId', '==', staffId))
.snapshotChanges()
.pipe(map(snaps => {
return snaps.map(snap => {
return <Notification>{
id: snap.payload.doc.id,
...Object.assign({}, snap.payload.doc.data())
}
});
}));
并在订阅时应用了我的所有逻辑:
this.notificationService.getNotifications(getStaffRolevalue(this.staffRole),
(this.staffRole === 'csa' || 'ops' || 'admin' ? null : this.loggedInStaffId)).subscribe(notifications => {
this.timer !== undefined ? this.timer.unsubscribe() : false;
this.timer = interval(5000)
.pipe(
map(tick => new Date()),
share()
).subscribe(date => {
this.notifications = notifications.filter(notification => notification.notificationDate <= date.getTime()).sort(function (a, b) { return b.notificationDate - a.notificationDate });
const x = this.notificationCount;
this.notificationCount = this.notifications.filter(notification => notification.isRead === 0).length;
const y = this.notificationCount;
y - x === 1 ? this.playAudio() : false;
});
});
关于javascript - 如何实时查询firestore?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61025204/