首页 > 解决方案 > 何时以角度取消订阅 SSE 事件源事件(关闭/刷新案例)

问题描述

我在我的应用程序的服务中使用了一些 EventSource。

我想在浏览器关闭/刷新时关闭所有连接。

我看过这个帖子

现在,这就是我添加到我的服务中的内容。

  @HostListener('window:beforeunload')
  onBrowserClose() {
    this.clearAll();
  }

  clearAll() {
    if (this.eventSource) {
      this.eventSource.close();
    }
    this.callbacks = new Map<string, (e: any) => void>();
  }

有更好的解决方案吗?

标签: angularserver-sent-eventseventsource

解决方案


您可以ngOnDestroy()用于取消订阅事件

ngOnDestroy() {
  if (this.eventSource) {
    this.eventSource.close();
  }
  this.callbacks = new Map<string, (e: any) => void>();
}

我想在浏览器关闭/刷新时关闭所有连接。

this angular life cycle method will be called when component is going to destroy

推荐阅读