Last active
January 15, 2019 18:23
-
-
Save alegut/8b498737821bb5f6fe198d6bec7e5757 to your computer and use it in GitHub Desktop.
Angular Intercaptors
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 { 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; | |
} | |
} |
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 { 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 {} |
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 { 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