Last active
April 21, 2019 06:19
-
-
Save kudchikarsk/ad170f0aa85d57057e2077c95892f5c2 to your computer and use it in GitHub Desktop.
Add Header using Interceptor on every http client request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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