Разрешить создание перехватчика http в угловом формате для управления действием при отправке запроса и получении ответа.
http.interceptor.ts
import { throwError as observableThrowError, Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Injectable, ErrorHandler } from '@angular/core';
import { UserStore } from '../store/user.store';
import { Router } from '@angular/router';
import * as HttpStatus from 'http-status-codes';
@Injectable()
export class SimpleHttpInterceptor implements HttpInterceptor {
constructor(private router: Router, private userStore: UserStore) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = this.addAuthentication(req);
return next.handle(req).pipe(catchError((err) => {
if (err.status === HttpStatus.UNAUTHORIZED) {
this.router.navigate(['/login']); //go to login fail on 401
}
return observableThrowError(err);
}));
}
//here you add the bearer in every request
addAuthentication(req: HttpRequest<any>): HttpRequest<any> {
const headers: any = {};
const authToken = this.userStore.getToken(); // get the token from a service
if (authToken) {
headers['authorization'] = authToken; // add it to the header
req = req.clone({
setHeaders: headers
});
}
return req;
}
}
Затем вы можете зарегистрировать его впример модуля
@NgModule({
imports: [
HttpClientModule
],
exports: [
HttpClientModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: UcmsHttpInterceptor, multi: true }
],
})
export class RestModule {