Skip to content

Instantly share code, notes, and snippets.

@octoberrust
Last active September 29, 2021 05:09
Show Gist options
  • Save octoberrust/ca29adc0b2ad423e7f39487e538ff543 to your computer and use it in GitHub Desktop.
Save octoberrust/ca29adc0b2ad423e7f39487e538ff543 to your computer and use it in GitHub Desktop.
interceptor
/** @format */
import {
HttpErrorResponse,
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Router } from "@angular/router";
import { Store } from "@ngrx/store";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";
import { AppState } from "src/app/store/store";
@Injectable({
providedIn: "root",
})
export class TokenInterceptorService implements HttpInterceptor {
public constructor(
private readonly router: Router,
private readonly store: Store<AppState>,
) {}
public intercept(
req: HttpRequest<any>,
next: HttpHandler,
): Observable<HttpEvent<any>> {
const jsonReq: HttpRequest<any> = req.clone({
setHeaders: {
Authorization: `Bearer ${localStorage.getItem("access_token")}`,
},
});
return next.handle(jsonReq).pipe(
tap(
() => {},
(err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status !== 401) {
return;
}
this.router.navigate(["/sign-in"]);
}
},
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment