review-request.js
import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class ReviewRequest implements HttpInterceptor {
constructor (private router : Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (localStorage.getItem('user') != null) {
const clonedReq = req.clone({
headers: req.headers.set('Authorization', 'Bearer' + localStorage.getItem('user'))
});
return next.handle(clonedReq).pipe(
tap(
succ => { },
err => {
if (err.status == 401) {
localStorage.removeItem('user');
this.router.navigateByUrl('/login');
}
}
)
)
}
else {
return next.handle(req.clone());
}
}
}
fetch-data.ts
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient, HttpBackend, HttpErrorResponse } from
'@angular/common/http';
import { User } from '../model/user';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class FetchData {
serverUrl = 'http://localhost:3000/api/user';
errorData = {};
httpOptions = {
headers: new HttpHeaders({'x-access-token' localStorage.getItem('user')})
};
private http: HttpClient
constructor(handler : HttpBackend) {
this.http = new HttpClient(handler)
}
addUser(formData) {
return this.http.post<User>(`${this.serverUrl}`, formData,
this.httpOptions).pipe(
catchError(this.handleError)
);
}
getUser() {
return this.http.get<User>(`${this.serverUrl}`, this.httpOptions).pipe(
catchError(this.handleError)
);
}
I have a query about injecting the HTTP interceptor to my service. I am confused on how to do it properly. The reason for needing this is because I have implemented authentication using JWT token. If a JWT token is provided, then the API will run, which needs to be integrated on the frontend as well. I have used the auth.interceptor to set the JWT token in the header, but I am unsure of how to inject it into the service. Can anyone please provide guidance on this issue?