Skip to content

Instantly share code, notes, and snippets.

@kavin-1103
Created July 26, 2023 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kavin-1103/bb647910293e51d7782cfd0d19849829 to your computer and use it in GitHub Desktop.
Save kavin-1103/bb647910293e51d7782cfd0d19849829 to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent } from '@angular/common/http';
import { NgxSpinnerService } from 'ngx-spinner';
import { Observable } from 'rxjs';
import { finalize,delay } from 'rxjs/operators';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private spinner: NgxSpinnerService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let token = localStorage.getItem('token');
// Show the spinner before the request is sent
this.spinner.show();
if (token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
}
// Handle the request and response
return next.handle(request).pipe(
delay(1000),
// Hide the spinner after the response is received
finalize(() => this.spinner.hide())
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment