Created
September 11, 2020 11:43
-
-
Save muhammadawaisshaikh/40dff47dd24ed87772b2c0daad57b634 to your computer and use it in GitHub Desktop.
http interceptor angular
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 { BrowserModule } from '@angular/platform-browser'; | |
import { NgModule } from '@angular/core'; | |
import { AppRoutingModule } from './app-routing.module'; | |
import { AppComponent } from './app.component'; | |
import { HttpClientModule } from '@angular/common/http'; | |
// for token interceptor | |
import { HTTP_INTERCEPTORS } from '@angular/common/http'; | |
import { TokenInterceptor } from '../app/core/interceptors/token.interceptor'; | |
// components | |
import { HomeComponent } from './components/home/home.component'; | |
import { UsersComponent } from './components/users/users.component'; | |
@NgModule({ | |
declarations: [ | |
AppComponent, | |
HomeComponent, | |
UsersComponent | |
], | |
imports: [ | |
BrowserModule, | |
AppRoutingModule, | |
HttpClientModule, | |
], | |
providers: [ | |
{ | |
provide: HTTP_INTERCEPTORS, | |
useClass: TokenInterceptor, | |
multi: true | |
} | |
], | |
bootstrap: [AppComponent] | |
}) | |
export class AppModule { } |
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 { | |
HttpRequest, | |
HttpHandler, | |
HttpEvent, | |
HttpInterceptor | |
} from '@angular/common/http'; | |
import { Observable } from 'rxjs'; | |
import { ConfigService } from '../http/config/config.service'; | |
@Injectable() | |
export class TokenInterceptor implements HttpInterceptor { | |
constructor( | |
private config: ConfigService | |
) {} | |
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
request = request.clone({ | |
setHeaders: { | |
Authorization: `Bearer ${this.config.getToken()}` | |
} | |
}); | |
console.log("Sending request with new header now ... INTERCEPTED"); | |
return next.handle(request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment