Created
August 18, 2018 10:49
-
-
Save svdamani/bfa895d8686ea6c73cc3efbfcfa84455 to your computer and use it in GitHub Desktop.
Angular Http Interceptor
This file contains 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 { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; | |
import { Injectable } from '@angular/core'; | |
import { Observable, throwError } from 'rxjs'; | |
import { catchError } from 'rxjs/operators'; | |
@Injectable() | |
export class RestInterceptor implements HttpInterceptor { | |
baseUrl: string; // base API url | |
token: string; // Initialize from login | |
constructor() {} | |
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
const url = `${this.baseUrl}/${request.url}`; | |
const setHeaders = { Authorization: this.token }; | |
request = request.clone({ url, setHeaders }); | |
return next.handle(request).pipe( | |
catchError( | |
(error: HttpErrorResponse): Observable<HttpEvent<any>> => { | |
// console.log(error); | |
// alert(error); | |
// this.someMessageService.send(error); | |
// error tracking API | |
return throwError(error); | |
} | |
) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment