So I created an angular2 module to handle HTTP Intercepting, using a basic interceptor like so:
@Injectable()
export class RequestInterceptor implements HttpInterceptor {
constructor(private injector: Injector) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authService = this.injector.get(AuthService);
if(authService.isAuthenticated()){
const authReq = request.clone({
setHeaders: {
Authorization: `Bearer ${authService.getAccessToken()}`
}
});
let handle = next.handle(authReq).do(event => {
if(event instanceof HttpResponse){
if(event.headers.has('Authorization')){
authService.updateToken(event.headers.get('Authorization').split(' ')[1]);
}
}
});
return handle;
}else{
return next.handle(request);
}
}
}
Which will add an authorization header to http requests and update its own header when a new one is sent from the server. Its imported and provided normally like so:
{
provide: HTTP_INTERCEPTORS,
useClass: RequestInterceptor,
multi: true
},
So the auth angular2 module is compiled and imported into my app.module.t, it works great. Until I tried to use it from a child module. The top answer from here: Inherit imports from parent module to child module in Angular2 claims that angular2 wont let you make things available globally to the whole app. Is this correct?
I got it working from the child module by just importing the RequestInterceptor, and setting it up in the providers for the module, but I'd rather not have to do so to make it less cumbersome to use.