bubbles
bubbles

Reputation: 2717

Angular : How to intercept Server-Sent Event request?

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.

Upvotes: 2

Views: 2838

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71911

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

Upvotes: 4

Related Questions