Skip to content

Instantly share code, notes, and snippets.

@alegut
Last active January 15, 2019 18:23
Show Gist options
  • Save alegut/8b498737821bb5f6fe198d6bec7e5757 to your computer and use it in GitHub Desktop.
Save alegut/8b498737821bb5f6fe198d6bec7e5757 to your computer and use it in GitHub Desktop.
Angular Intercaptors
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { AuthService } from '../auth/auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('Intercepted!', req);
// const copiedReq = req.clone({headers: req.headers.set('', '')});
const copiedReq = req.clone({params: req.params.set('auth', this.authService.getToken())});
return next.handle(copiedReq);
// return null;
}
}
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from '../shared/auth.interceptor';
import { LoggingInterceptor } from '../shared/logging.interceptor';
@NgModule({
declarations: [
HeaderComponent,
HomeComponent
],
imports: [
SharedModule,
AppRoutingModule
],
exports: [
AppRoutingModule,
HeaderComponent
],
providers: [
AuthService,
{provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true},
{provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true}
]
})
export class CoreModule {}
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { tap } 'rxjs/operators';
export class LoggingInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(tap(
event => {
console.log('Logging interceptor', event);
}
)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment