Как запросить пожарный магазин в реальном времени? - PullRequest
2 голосов
/ 04 апреля 2020

Итак, в коллекции уведомлений хранится список объектов уведомлений, и моя цель - получить все уведомления, которые старше текущей даты и времени.

Итак, мой базовый запрос c был:

    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;
      });
  });

Мой лог c должен был повторять подписку на наблюдаемую каждую секунду. Это сработало, но использование базы данных для чтения документов взлетело до небес. Так что, в принципе, эту логику c также нельзя использовать.

Есть ли другой способ добиться того, чего я пытаюсь достичь. Я открыт для любых предложений, даже если речь идет об изменении моего интерфейса, если я получаю уведомления относительно реального времени.

Интерфейс:

export interface Notification {
    id: string,
    isRead: number,
    jobNo: number,
    notificationDate: number,
    notificationMessage: string,
    notificationTitle: string,
    notificationType: number,
    receiverId: string,
    staffRole: number
}

1 Ответ

2 голосов
/ 04 апреля 2020

Я изменил свой запрос в сервисе на простой запрос:

        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())
              }
            });
          }));

И применил все мои логи c, пока я подписывался:

    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;
          });
      });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...