I am in the process of building a new app that requires authorization headers. Typically I use something very similar to the approach found in this scotch.io article. But it has come to my attention that HTTP Interceptors are now fully supported within the Angular 4 ecosystem via the new HttpClientModule and I am trying to find some documentation on how exactly to use them.
If I am incorrect in (as of 4.3) this being the best practice for injecting authorization headers, I'd also be open to suggestions. My thinking was that it was a feature added recently which means there is probably good reason to migrate to an "Angular Approved" method.
This answer is borrowing from the official documentation linked to by CodeWarrior.
Angular allows you to create an HttpInterceptor:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req);
}
}
which you can then integrate into your app like so:
import {NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS} from '@angular/common/http';
@NgModule({
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: NoopInterceptor,
multi: true,
}],
})
export class AppModule {}
To add an authorization header, you can clone the request with the changed headers:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get the auth header from the service.
const authHeader = this.auth.getAuthorizationHeader();
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
// Pass on the cloned request instead of the original request.
return next.handle(authReq);
}
}
Note that the interceptors act like a chain, so you can set up multiple interceptors to perform different tasks.