How to intercept HTTP Calls in AWS Amplify with Angular

Viewed 284

Problem Statement: I have working on project in Angular using AWS Amplify. The project uses cognito and successfully created AWS api for client calls. Now, I need an interceptor to intercept the requests as I need to do perform some action.

What I DID:

I have tried using Angular HTTP Interceptors but they don't work. According to my research that AWS Amplify uses axios interceptors under the hood to intercept the calls. I tried implementing using Axios package https://www.npmjs.com/package/axios

My Implementation:

MyIntercept.ts

    import { Injectable } from '@angular/core';
       import axios from 'axios';    
       @Injectable({providedIn: 'root'})
       export class MyInterceptor {
          intercept() {
             console.log("Hello this is my interceptor")
             axios.interceptors.request.use(request => {
                console.log("*******************Inside My Interceptor*************");
                console.log("Call: ", request);
                return request;
                });
            }
       }

export function InterceptorFactory(myIntercept: MyInterceptor): any {
  return () => myIntercept.intercept();
}

and in the app Module file

    import { InterceptorFactory, MyInterceptor } from './myInterceptor.service';
    import { APP_INITIALIZER } from '@angular/core';
    
    providers: [
        {
            provide: APP_INITIALIZER,
            useFactory: InterceptorFactory,
            deps: [MyInterceptor],
            multi: true
        }
    ]

What I get:

When I run the code, all I see the line outside the console for once only which is:

Hello this is my interceptor

I need to ask you if I am doing something wrong here or is there any other approach to achieve this?

0 Answers
Related