Skip to content

Instantly share code, notes, and snippets.

@belachkar
Last active November 14, 2021 08:40
Show Gist options
  • Select an option

  • Save belachkar/955d58757a015916762a892b8992381c to your computer and use it in GitHub Desktop.

Select an option

Save belachkar/955d58757a015916762a892b8992381c to your computer and use it in GitHub Desktop.

Angular interceptors

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 {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment