DEV Community

Cover image for Use Http interceptor In Angular for Every Http Request
Sandeep
Sandeep

Posted on

Use Http interceptor In Angular for Every Http Request

sometimes we are using HttpClient in angular for api request to add some additional information through headers to send request to server.
first we add HttpModule in app.module.ts imports array.

http.interceptors.ts

import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpErrorResponse, HttpHeaders } from "@angular/common/http";
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

@Injectable()

export class HttpTokenInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        const headersConfig = {
            'Accept': 'application/json'
        };
        const idToken = localStorage.getItem("token");

        if (idToken) {
            headersConfig['Authorization'] = idToken;
            let request = req.clone({
                setHeaders: headersConfig
            });
            return next.handle(request);
        }
        else {
            return next.handle(req)
        }
        // // authorization with jwt token
        // let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        // if (currentUser && currentUser.token) {
        //     let request = req.clone({
        //         setHeaders: {
        //             Authorization: `Bearer ${currentUser.token}`
        //         }
        //     });
        // }

        // return next.handle(req);
    }
}
Enter fullscreen mode Exit fullscreen mode

api.service.ts

import { Injectable } from '@angular/core';
import { Observable } from "rxjs";
import { environment } from "../../../environments/environment";
import { HttpHeaders, HttpClient, HttpParams } from "@angular/common/http";
import { throwError } from "rxjs";
import { catchError, retry } from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  httpOptions = {
    headers: new HttpHeaders({
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*"
    })
  };
  constructor(private http: HttpClient) { }

  private formatErrors(error: any) {
    return throwError(error.error);
  }

  get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
    return this.http.get(path, { params }).pipe(catchError(this.formatErrors));
  }

  put(path: string, body: Object = {}): Observable<any> {
    return this.http
      .put(path, JSON.stringify(body), this.httpOptions)
      .pipe(catchError(this.formatErrors));
  }

  post(path: string, body: Object = {}): Observable<any> {
    return this.http
      .post(path, JSON.stringify(body), this.httpOptions)
      .pipe(catchError(this.formatErrors));
  }

  delete(path): Observable<any> {
    return this.http.delete(path).pipe(catchError(this.formatErrors));
  }
}


Enter fullscreen mode Exit fullscreen mode

thats it developers.

Top comments (1)

Collapse
 
deepakjaiswal profile image
Sandeep

I miss to add in providers that is
{ provide: HTTP_INTERCEPTORS, useClass: HttpTokenInterceptor, multi: true }.