Angular : How to intercept Server-Sent Event request?

2.2k Views Asked by At

I've written an angular interceptor to add some headers to my requests. Everything's fine till the SSE request, it is not intercepted !

@Injectable()
export class SessionUserDataInterceptor implements HttpInterceptor {

  constructor(@Inject(SESSION_USER_DATA) private userData: SessionUserData) {}


  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const setHeaders = {};

    if (this.userData.line) {
      setHeaders['Line'] = this.userData.line;
    }

    if (this.userData.profil) {
      setHeaders['Profil'] = this.userData.profil.id;
    }

    return next.handle(request.clone({setHeaders}));
  }
}

SessionUserData is just a wrapper for the SessionStorage.

I've tried to add the headers to my SSE connection but it's not working neither.

const es = new EventSource(url, {headers: {Line: 'XXX', Profil: 'YYY'}} as any);

Any help's appreciated.

1

There are 1 best solutions below

8
On BEST ANSWER

The HttpInterceptor pattern only works for request sent by the HttpClient. Which means that EventSource is not captured, neither is an ordinary XMLHttpRequest. Best thing you could do is to move the actual transformation of your request in your interceptor to a utility function, which you can call inside your interceptor and perhaps a custom service which wraps the EventSource functionality