Skip to content

Instantly share code, notes, and snippets.

@svdamani
Created August 18, 2018 10:49
Show Gist options
  • Save svdamani/bfa895d8686ea6c73cc3efbfcfa84455 to your computer and use it in GitHub Desktop.
Save svdamani/bfa895d8686ea6c73cc3efbfcfa84455 to your computer and use it in GitHub Desktop.
Angular Http Interceptor
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