Move interceptor to other file

This commit is contained in:
Matteo Gheza 2022-01-04 00:19:55 +01:00
parent cb841269e7
commit 34916cb654
3 changed files with 26 additions and 24 deletions

View File

@ -0,0 +1,23 @@
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, tap } from 'rxjs';
import { AuthService } from '../_services/auth.service';
@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe( tap({
next: () => {},
error: (err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status !== 401 || request.url.includes('/login')) {
return;
}
console.log("Login required");
this.auth.logout();
}
}}));
}
}

View File

@ -1,7 +1,5 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, tap } from 'rxjs';
import { AuthService } from './auth.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
@ -81,23 +79,3 @@ export class ApiClientService {
});
}
}
@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe( tap({
next: () => {},
error: (err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status !== 401) {
return;
}
console.log("Login richiesto");
this.auth.logout();
//this.router.navigate(['login']);
}
}}));
}
}

View File

@ -2,7 +2,6 @@ import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { UnauthorizedInterceptor } from './_services/api-client.service';
import { FormsModule } from '@angular/forms';
import { ToastrModule } from 'ngx-toastr';
import { ModalModule } from 'ngx-bootstrap/modal';
@ -24,6 +23,8 @@ import { LogsComponent } from './_components/logs/logs.component';
import { ServicesComponent } from './_components/services/services.component';
import { TrainingsComponent } from './_components/trainings/trainings.component';
import { UnauthorizedInterceptor } from './_providers/unauthorized-interceptor.provider';
@NgModule({
declarations: [
AppComponent,