Angular 8 - 来自 websocket 的输入指示器

Angular 8 - Typing indicator from websocket

我目前正在 Angular 8 中进行网络聊天。我已连接到 websocket,并且我正在接收有关有人正在键入消息的信息。它被称为"Typing indicator"。每当有人向我输入内容时,我都会得到这些信息。不幸的是,我没有收到有人停止输入的信息,我需要实现逻辑,如果有人停止输入,我只显示输入指示器 4 秒。

public showTypingIndicator() {
  const currentDate = new Date();
  currentDate.setSeconds(currentDate.getSeconds() - 4);

  return this.lastTypingDate !== null && this.lastTypingDate > currentDate;
}

我的 this.lastTypingDate 我从我的服务中获取,以防万一在我的 websocket 中收到类型为 "Typing-indicator" 的消息,然后我将其设置为 this.lastTypingDate = new Date();。这就是我将数据从我的服务传递到此变量的方式:this.myDateService.getLastTypingDate().

这有效,但它显示我的打字指示器的时间超过 4 秒。有什么想法可以在这里更改以使其按预期工作吗?

提前致谢!

您可以将 showTypingIndicator 函数更改为 getter 并以秒为单位比较日期吗?

public get showTypingIndicator() {
    const currentSeconds = (new Date()).getTime()/1000;
    return !!this.lastTypingDate && (currentSeconds - (this.lastTypingDate.getTime()/1000)) < 5;
}

每当您的服务更新 lastTypingDate 时,showTypingIndicator 都会得到评估。有功能,每次都需要调用

我通过使用 rxjs 和 BehaviorSubject 解决了这个问题。 仅当订阅收到一些数据时,我才将 BehaviorSubject 的值传递给 true。