Last active
September 29, 2021 05:09
-
-
Save octoberrust/ca29adc0b2ad423e7f39487e538ff543 to your computer and use it in GitHub Desktop.
interceptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @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