1. 实时通信架构决策矩阵

技术维度选型方案替代方案决策依据
实时通信协议Server-Sent Events (SSE)WebSocket / 短轮询 (Polling)业务为服务端向客户端单向广播;复用标准 HTTP 基础设施与网关,原生支持断线自愈重连。
SSR 宿主守卫isPlatformBrowser 判定为 false 时直接 complete()服务端尝试建立连接或抛异常Node.js 运行时缺少原生 EventSource,服务端阶段立即完成流,杜绝渲染挂起与致命报错。
事件路由分发addEventListener('NEW_BOOK', ...)原生 eventSource.onmessage后端采用具名事件推送;利用浏览器底层事件总线直接过滤,避免应用层进行无意义的类型判断。
连接断线重试onerror 仅记录日志,严禁调用 subscriber.error()遇到网络中断直接触发 error 终结流触发 subscriber.error 将导致 RxJS 流彻底报废,保留由浏览器内核执行自动指数退避重连。
自反事件去重客户端 Set 记录规范化 ISBN 进行自创建抑制仅依赖服务端过滤或忽略重复消除本端提交成功后的重复弹窗与二次重载,消除网络延迟带来的视图抖动。

2. 生产级 NotificationService:RxJS EventSource 封装范式

typescript
import { Injectable, PLATFORM_ID, inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { Observable } from 'rxjs';
import { environment } from '../../../../environments/environment';
import { BookNotification } from '../../../shared/models/notification';
 
@Injectable({ providedIn: 'root' })
export class NotificationService {
  private readonly platformId = inject(PLATFORM_ID);
  private readonly streamUrl = `${environment.apiUrl}/inventory/api/notifications/stream`;
 
  /**
   * 建立 SSE 响应式数据流连接
   */
  connect(): Observable<BookNotification> {
    return new Observable<BookNotification>((subscriber) => {
      // 1. SSR 平台环境防护:Node.js 环境直接完成,防止找不到 EventSource
      if (!isPlatformBrowser(this.platformId)) {
        subscriber.complete();
        return;
      }
 
      // 2. 初始化浏览器原生 EventSource
      const eventSource = new EventSource(this.streamUrl);
 
      // 3. 定向监听后端广播的 NEW_BOOK 具名事件
      eventSource.addEventListener('NEW_BOOK', (event: Event) => {
        try {
          const messageEvent = event as MessageEvent;
          const parsed = JSON.parse(messageEvent.data) as BookNotification;
          subscriber.next(parsed);
        } catch (error) {
          console.error('[NotificationService] SSE JSON parse error:', error);
        }
      });
 
      // 4. 容错处理:切勿调用 subscriber.error(),以便保留浏览器原生重连机制
      eventSource.onerror = () => {
        console.warn('[NotificationService] SSE connection interrupted. Browser will reconnect...');
      };
 
      // 5. 资源清理回收:当外部 Observable 发生取消订阅时关闭 TCP 长连接
      return () => {
        eventSource.close();
      };
    });
  }
}

3. 消费端闭环:生命周期绑定、自创建去重与搜索防冲刷

typescript
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatDialog } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { injectDispatch } from '@ngrx/signals/events';
import { BookStore } from '../../store/book-store/book.store';
import { bookPageEvents } from '../../store/book-store/book.events';
import { NotificationService } from '../../services/notification.service';
import { BookForm } from '../../components/book-form/book-form';
 
export class List implements OnInit {
  protected readonly store = inject(BookStore);
  protected readonly dispatch = injectDispatch(bookPageEvents);
  private readonly dialog = inject(MatDialog);
  private readonly snackBar = inject(MatSnackBar);
  private readonly notificationService = inject(NotificationService);
  private readonly destroyRef = inject(DestroyRef);
 
  // 本地已提交待确认的 ISBN 白名单(用于自发推送拦截)
  private readonly locallyCreatedIsbns = new Set<string>();
 
  ngOnInit(): void {
    this.dispatch.loadBooks({ page: 0, size: 10 });
 
    // 订阅实时事件流,绑定组件生命周期
    this.notificationService
      .connect()
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe((notification) => {
        const normalizedIsbn = notification.isbn ? this.normalizeIsbn(notification.isbn) : null;
 
        // 核心自反去重:若通知源于本地刚刚提交的创建操作,静默消费并退出
        if (normalizedIsbn && this.locallyCreatedIsbns.has(normalizedIsbn)) {
          this.locallyCreatedIsbns.delete(normalizedIsbn);
          return;
        }
 
        // 外部新书推送提示
        this.snackBar.open(`📚 New book added: ${notification.bookTitle}`, 'Dismiss', { duration: 5000 });
 
        // 搜索态保护:非搜索模式下方自动重载列表,避免冲刷用户当前查询结果
        if (!this.store.isSearching()) {
          this.dispatch.loadBooks({
            page: this.store.currentPage(),
            size: this.store.pageSize(),
          });
        }
      });
  }
 
  openCreateDialog(): void {
    const dialogRef = this.dialog.open(BookForm, { width: '560px' });
    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        this.locallyCreatedIsbns.add(this.normalizeIsbn(result.isbn));
        this.dispatch.createSubmitted(result);
        this.snackBar.open('Book created successfully', 'Close', { duration: 3000 });
      }
    });
  }
 
  private normalizeIsbn(isbn: string): string {
    return isbn.replace(/[-\s]/g, '');
  }
}

4. SSE 广播与自发事件拦截时序拓扑

流程架构图
Mermaid

5. SSE 实时通信避坑清单 (Do's & Don'ts)

错误实践 (Don't)正确实践 (Do)
在 eventSource.onerror 回调中调用 subscriber.error(err)。仅输出警告日志,保留浏览器原生指数退避自动重连能力,避免流永久冻结。
未针对 SSR 平台进行隔离,导致在 Node.js 中执行 new EventSource()。注入 PLATFORM_ID 校验,在非浏览器宿主中直接调用 subscriber.complete() 正常终结。
忽略组件销毁生命周期,未进行长连接注销清理。在 Observable Teardown 中执行 eventSource.close(),并搭配 takeUntilDestroyed 自动取消订阅。
客户端收到新书推送时不假思索强行重置刷新分页列表。判断 isSearching() 状态,若用户正处于搜索筛选状态,则保留当前视图仅作通知提示。
缺乏客户端去重机制,用户自身创建数据后被自己的 SSE 消息二次弹窗干扰。引入 Correlation Key(如标准化 ISBN)集合,对本地触发的异步回环事件实施静默拦截。