1

I am trying to implement an angular application where I will make API calls to backend to get data. How can I create an Interceptor to make requests(GET, POST, PUT, DELETE) to backend urls. Also there are some specif routes that require an authorisation token.

Also, I want to handle specif tasks based on response status codes. If backend returns 401 or 500, 202 (has a refresh token) then I want to handle them accordingly. Also, is there any way to subscribe to the request from angular components.

As a beginner I dont have much idea how to create this in flexible way, so that if my application grows in future that it will not create any problem.

1 Answer 1

1

Check the following interceptor template to handle sending token in header ,refresh token and handle errors based on response status

import {
    HttpRequest,
    HttpHandler,
    HttpEvent,
    HttpInterceptor,
    HttpErrorResponse,
    HttpHeaders,
    HttpClient
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, flatMap } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';

@Injectable({
    providedIn: 'root'
})
export class HttpConfigInterceptor implements HttpInterceptor {

    constructor(private httpClient: HttpClient) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        const token = "my-token-string-from-server";

        //Authentication by setting header with token value
        if (token) {
            request = request.clone({
                setHeaders: {
                    'Authorization': token
                }
            });
        }

        if (!request.headers.has('Content-Type')) {
            request = request.clone({
                setHeaders: {
                    'content-type': 'application/json'
                }
            });
        }

        request = request.clone({
            headers: request.headers.set('Accept', 'application/json')
        });

        return next.handle(request).pipe(
            catchError((error: HttpErrorResponse) => {
                if (error.status == 401 && error.error) {
                    return this.refreshToken(next, request);
                }
                return throwError(this.handleError(error));
            }));
    }

    handleError(error) {
        if (error.status == 400) {

        } else if (error.status == 422) {

        } else if (error.status = 404) {

        }
    }

    refreshToken(next, request): Observable<any> {
        var header = new HttpHeaders({
            "refreshToken": "refreshToken",
            "token": "token"
        });
        var url = environment.apiUrl + "/refreshToken";
        return this.httpClient.get(url, { headers: header }).pipe(
            flatMap(response => {
                //console.log(response);
                // save new token
                request = request.clone({ headers: request.headers.set('token', (<any>response).token) });
                return next.handle(request).pipe(
                    catchError(error => {
                        return throwError(this.handleError(error))
                    })
                )
            }),
        )
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.