Skip to content

Instantly share code, notes, and snippets.

@prosenjit-manna
Created June 5, 2018 21:14
Show Gist options
  • Save prosenjit-manna/5ce00228883ce6166e65b9eb1862c7c7 to your computer and use it in GitHub Desktop.
Save prosenjit-manna/5ce00228883ce6166e65b9eb1862c7c7 to your computer and use it in GitHub Desktop.
angular 6 interceptor
import {
Injectable,
// Injector
} from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse
} from '@angular/common/http';
// import { Router } from '@angular/router';
import { catchError } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
// import { AuthService } from './auth.service';
import { environment } from '../environments/environment';
@Injectable()
export class AppInterceptor implements HttpInterceptor {
constructor(
// private injector: Injector,
// private router: Router
) { }
private includeWooAuth(url) {
const wooAuth = `consumer_key=${environment.woocommerce.consumer_key}&consumer_secret=${environment.woocommerce.consumer_secret}`;
const hasQuery = url.includes('?');
let return_url = '';
if (hasQuery) {
return_url = wooAuth;
} else {
return_url = '?' + wooAuth;
}
return return_url;
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// const auth = this.injector.get(AuthService);
const authRequest = request.clone({
setHeaders: {
// Authorization: `Bearer ${auth.getToken()}`
},
url: `${environment.origin}/${request.url}${this.includeWooAuth(request.url)}`
});
return next.handle(authRequest)
.pipe(
catchError(err => {
if (err instanceof HttpErrorResponse && err.status === 0) {
console.log('Check Your Internet Connection And Try again Later');
} else if (err instanceof HttpErrorResponse && err.status === 401) {
// auth.setToken(null);
// this.router.navigate(['/', 'login']);
}
return throwError(err);
})
);
}
}
@kumarandena
Copy link

Good work @prosenjit-itobuz. Can you please add the part of handling/retry failed request with this gist.

(https://gist.github.com/prosenjit-itobuz/5ce00228883ce6166e65b9eb1862c7c7#file-http-interceptor-ts-L53)
In my case After getting error status 401, I am making http call to get new access token by using refresh token. Now i need to continue/retry the failed request inside interceptor itself and have to send the response to the component in one shot.

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