http-errors-interceptor.ts:
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, Observable, throwError } from 'rxjs';
@Injectable()
export class HttpErrorsInterceptor implements HttpInterceptor {
constructor() {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((err) => {
const error = err.message || err;
console.log(error);
return throwError(() => new Error(error));
})
);
}
}http-headers-interceptor.ts:
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
@Injectable()
export class HttpHeadersInterceptor implements HttpInterceptor {
constructor() {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
'X-RapidAPI-Key': environment['X-RapidAPI-Key'],
'X-RapidAPI-Host': environment['X-RapidAPI-Host'],
},
setParams: {
key: environment['API_KEY'],
},
});
return next.handle(req);
}
}app.module.ts:
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';
// Local
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpHeadersInterceptor } from './interceptors/http-headers-interceptor';
import { HttpErrorsInterceptor } from './interceptors/http-errors-interceptor';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
HttpClientModule,
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpHeadersInterceptor,
multi: true,
},
{
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorsInterceptor,
multi: true,
},
],
bootstrap: [AppComponent],
})
export class AppModule {}