EventSource не обновляется при нескольких событиях - PullRequest
0 голосов
/ 04 июня 2019

У меня есть следующий код

@Injectable({
  providedIn: 'root'
})
export class SSEService {
  private eventSource: EventSource;
  private callbacks: Map<string, (e: any) => void> = new Map<string, (e: any) => void>();

  constructor() {
    this.init(environment.channelName);
  }

  init(channel: string) {
    if (this.eventSource) { return; }

    this.eventSource = new EventSource(`${environment.SSE_URL}?channel=${channel}`);
    this.eventSource.onmessage = (e) => {console.log('Connected');};
  }

  protected callListener(cb: (d) => void): (e) => void {
    const callee = ({data}): void => {
      const d = JSON.parse(data);
      cb(d.message);
    };
    return callee;
  }

  private addEventToEventSrc(event: string, callback: any, owner: string): void {
    console.log(`Subscribed to ⇢ ${event} (owned by: ${owner})`);
    const cb = this.callListener(callback);
    this.eventSource.addEventListener(event, cb);
    if (!this.callbacks.get(`${event}_${owner}`)) {
        this.callbacks.set(`${event}_${owner}`, cb);
    }
  }

  subscribe(event: string, callback: any, owner?: string): void {
    if (!this.eventSource) { return; }
    if (!owner) { owner = 'default'; }
    if (!event) { event = 'message'; }
    this.addEventToEventSrc(event, callback, owner);
}

  unsubscribe(event: string, owner?: string): void {
    if (!this.eventSource) { return; }
    if (!owner) { owner = 'default'; }
    if (!event) { event = 'message'; }
    if (this.callbacks.get(`${event}_${owner}`)) {
      console.log(`Unsubscribed to ⇢ ${event} (owned by: ${owner})`);
      this.eventSource.removeEventListener(event, this.callbacks.get(`${event}_${owner}`));
    }
    this.callbacks.delete(`${event}_${owner}`);
  }

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

В другом месте кода я подписываюсь на 2 события

this.sseService.subscribe(`get_position_1`, (val) => {   console.log(val)});
this.sseService.subscribe(`get_rotation_1`, (val) => {   console.log(val)});

Проблема в том, что, если я подпишусь на этот канал, после некотороговремя, когда я больше не получаю обновления (даже если сервер продолжает отправлять обновления).Если я не подпишусь дважды, я получу все обновления без сокращений.

Я не понимаю свою ошибку в SSEService, поэтому я хотел бы, чтобы кто-то еще дважды проверил, есть ли у вас время.

...