我有以下代码
@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中的错误,因此我希望其他人再次检查您是否有空。