Skip to content

Instantly share code, notes, and snippets.

@kumar-muthu
Created January 19, 2019 19:16
Show Gist options
  • Save kumar-muthu/87c1404d3da48702739183e8d2c6e7d5 to your computer and use it in GitHub Desktop.
Save kumar-muthu/87c1404d3da48702739183e8d2c6e7d5 to your computer and use it in GitHub Desktop.
Angular HTTP Interceptor
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpResponse,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse
} from '@angular/common/http';
import { Observable, EMPTY, throwError } from 'rxjs';
import { switchMap, catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import {AngularFireAuth} from 'angularfire2/auth';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private afAuth: AngularFireAuth) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (request.url.includes('api.imgur.com')) {
return next.handle(request);
} else {
return this.afAuth.idToken
.pipe(switchMap((token) => {
const config = {
setHeaders: {
Authorization: `Bearer ${token}`
}
};
const user = JSON.parse(localStorage.getItem('user'));
if (user && user.activeGroup) {
config['url'] = request.url.replace(':groupid', user.activeGroup.id);
}
const reqClone = request.clone(config);
return next.handle(reqClone);
}));
}
}
}
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private afAuth: AngularFireAuth, private router: Router) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 401) {
// auto logout if 401 response returned from api
localStorage.removeItem('user');
// this.afAuth.auth.signOut();
// location.reload(true);
} else if (err.status === 403) {
this.router.navigate(['/unauthorized']);
} else if (err.status === 500) {
err.statusText = 'Oops';
err.error.error.message = 'Something went wrong!';
}
const error = {
title: err.statusText || 'Oops!',
message: err.error.error.message || 'Something went wrong!'
};
return throwError(error);
}));
}
}
@kumar-muthu
Copy link
Author

kumar-muthu commented Jan 19, 2019

should take(1) instead of continuing to subscribe at line #47

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment