I'm working on an angular 6 app where I want to add an jwt-token to the authorize-header of every request. For this scenario I want to use an interceptor.
The code looks like this:
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let sessionId = localStorage.getItem('sessionId');
if (sessionId) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${sessionId}`
}
});
console.log("With AuthHeader");
}
return next.handle(request);
}
}
Here is my code for sending the request:
httpQuery(ressource): Observable<T[]> {
var absoluteUrl = this.getAbsoluteUrl(ressource);
console.log("Sending");
return this.httpClient
.get<T[]>(absoluteUrl);
}
However I face the following problem:
The interceptor gets fired, but AFTER the request is sent. I can see this in developer console where the log-message from the http-method comes right before the log-message from the interceptor:

As you can see, this leeds to a 401 response from the server which expects the authorization-header.
I read a ton of tutorials and stackoverflow-questions about interceptor, but I can't see my mistake.
Maybe some of guys have a hint for me?
Thank you and best regards, Alex