I'm trying to implement SSE and running into this error regarding onmessage. This is my code:
import {Injectable} from "@angular/core";
import {Observable} from "rxjs";
import {AService} from "./a.service";
import {EventSourcePolyfill} from "event-source-polyfill";
@Injectable({
providedIn: "root",
})
export class SseService {
private eventSource!: EventSourcePolyfill | null;
public constructor(private aService: AService) {}
public getServerSentEvent(url: string): Observable<MessageEvent> {
const token = this.aService.config.authorization;
const headers = {Authorization: `Bearer ${token}`};
return new Observable<MessageEvent>((observer) => {
this.eventSource = new EventSourcePolyfill(url, {
withCredentials: false,
headers,
});
this.eventSource.onmessage = (event: MessageEvent): void => {
observer.next(event);
};
this.eventSource.onerror = (error): void => {
observer.error(error);
};
return () => {
this.eventSource?.close();
};
});
}
public closeEventSource(): void {
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
}
}
}
I'm getting this error on line this.eventSource.onmessage = (event:MessageEvent)...
Type '(event: MessageEvent) => void' is not assignable to type '(this: EventSource, ev: MessageEvent) => any'. Types of parameters 'event' and 'ev' are incompatible. Type 'MessageEvent' is missing the following properties from type 'MessageEvent': origin, ports, source, initMessageEvent, and 20 more.ts(2322) (property) SseService.eventSource: EventSourcePolyfill
I tried adding a custom message event but that didn't fix my issue and typescript doesn't allow "any" type so that's out of the question. I'm not sure if this is of any relevance to the solution but I do need to pass the token as a header so passing it through as a query parameter is out of the question.