Skip to content

Instantly share code, notes, and snippets.

@kudchikarsk
Last active April 21, 2019 06:19
Show Gist options
  • Select an option

  • Save kudchikarsk/ad170f0aa85d57057e2077c95892f5c2 to your computer and use it in GitHub Desktop.

Select an option

Save kudchikarsk/ad170f0aa85d57057e2077c95892f5c2 to your computer and use it in GitHub Desktop.
Add Header using Interceptor on every http client request
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(`AddHeaderInterceptor - ${req.url}`);
let jsonReq: HttpRequest<any> = req.clone({
setHeaders: {'Content-Type': 'application/json'}
});
return next.handle(jsonReq);
}
}
/*
Configure interceptor in module
...
import { NgModule, Optional, SkipSelf, ErrorHandler } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AddHeaderInterceptor } from './add-header.interceptor';
...
...
@NgModule({
imports: [
CommonModule
],
declarations: [],
providers: [
LoggerService,
DataService,
{ provide: HTTP_INTERCEPTORS, useClass: AddHeaderInterceptor, multi: true },
...
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment