A step-by-step guide on implementing an HTTP interceptor in a service

review-request.js

import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';


@Injectable()

export class ReviewRequest implements HttpInterceptor {

constructor (private router : Router) {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (localStorage.getItem('user') != null) {
        const clonedReq = req.clone({
            headers: req.headers.set('Authorization', 'Bearer' + localStorage.getItem('user'))
        });
        return next.handle(clonedReq).pipe(
            tap(
                succ => { },
                err => {
                    if (err.status == 401) {
                        localStorage.removeItem('user');
                        this.router.navigateByUrl('/login');
                    }
                }
            )
        )
    }
    else {
        return next.handle(req.clone());
    }
}
}

fetch-data.ts

import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient, HttpBackend, HttpErrorResponse } from 
'@angular/common/http';
import { User } from '../model/user';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
  })   
 export class FetchData {
serverUrl = 'http://localhost:3000/api/user';
 errorData = {};

 httpOptions = {
    headers: new HttpHeaders({'x-access-token' localStorage.getItem('user')})
 };

 private http: HttpClient
 constructor(handler : HttpBackend) { 
  this.http = new HttpClient(handler)
 }

  addUser(formData) {
return this.http.post<User>(`${this.serverUrl}`, formData, 
 this.httpOptions).pipe(
  catchError(this.handleError)
  );
 }

 getUser() {
return this.http.get<User>(`${this.serverUrl}`, this.httpOptions).pipe(
  catchError(this.handleError)
);
  }

I have a query about injecting the HTTP interceptor to my service. I am confused on how to do it properly. The reason for needing this is because I have implemented authentication using JWT token. If a JWT token is provided, then the API will run, which needs to be integrated on the frontend as well. I have used the auth.interceptor to set the JWT token in the header, but I am unsure of how to inject it into the service. Can anyone please provide guidance on this issue?

Answer №1

I am struggling with injecting an http interceptor into a service. I need some guidance on how to accomplish this.

To inject interceptors in your app.module.ts, add them to the provider's array as shown below:~

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({
  imports: [HttpClientModule],
  providers: [
    AuthService, // token retrieval
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
    UserService
  ]
})

If you need to access AuthService within your AuthInterceptor to retrieve the token, make sure to inject it into the constructor of AuthInterceptor and utilize it accordingly:~

import { Injectable, Injector } from '@angular/core';

export class AuthInterceptor implements HttpInterceptor {
  constructor(
    private injector: Injector,
    private router: Router
  ) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('Intercepted!', req);
    const authService = this.injector.get(AuthService);
    
    const copiedReq = req.clone({
      headers: req.headers.set(
        'authorization', 'Bearer ' + authService.token
      )
    });
    // Additional logic goes here..
  }
}

(Your AuthService can fetch the token, store it in localStorage, and proceed with implementation)

Check out a working STACKBLITZ demo app for sample JWT authentication here

I hope this information proves helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting TestBed: Resolving the StatusBar Provider Error

After reading an informative article on testing Ionic2 projects with TestBed, I encountered difficulties when trying to replicate the example in my own environment. When attempting to initiate tests at Step 3, I encountered the error message stating "No pr ...

``Implementing a method to save the output of an asynchronous request in a global variable for future manipulation

It's been a week and I still can't figure this out. Being new to front-end development, I'm struggling with storing the response from subscribe in a global variable for future use. ngOnInit(): void { this.http.get<APIResponse>('ur ...

Having difficulties viewing the sidemenu icon on Ionic 3, despite enabling the menu through MenuController

I am trying to show the sidemenu icon on my Home page, which users can access from the Add-Contract page. Even though I have enabled the sidemenu in home.ts using this.menu.enable(true);, the icon is not visible. However, I can still swipe and access the ...

Limitation in Angular: Unable to utilize Scss in newly created components

Upon review, an error was identified as follows: https://i.sstatic.net/8JJsQ.png [WDS] Compilation errors detected. Reload interrupted. ./src/app/products/products.component.sass Error encountered during module build process (from ./node_modules/sass ...

Guide to showcasing a maximum of five cards per row using Angular Material within an NgFor loop

After receiving an array of around 1000 contacts from the API, I want to display them in contact cards. My requirement is to show a maximum of 5 contact cards in each row. Additionally, I am looking for pagination functionality similar to Angular Material ...

Polling database from various browser tabs

Working on a .NET/angular application that regularly checks the SQL Server database for updates, with the user able to customize the polling interval starting from 10 seconds (as per business requirements). The issue arises when each new tab opened by a ...

Acquiring user information from Firebase using Angular 2

Here's a signup code snippet that pertains to my previous inquiry on Stack Overflow about adding user data upon account creation. The code is as follows: signup(){ firebase.auth().createUserWithEmailAndPassword(useremail, userpassword) .then(fu ...

Comparing the Features of Angular 7 and Angular 8

Could someone explain the key distinctions between Angular 7 and Angular 8, especially focusing on the significant new addition of the IVY engine? I would appreciate details or a link to delve deeper into this concept for better understanding. ...

The type 'string' cannot be assigned to the type '"GET" | "get" | ...'

In my custom hook, I utilize the axios library for making requests: const useCustomHook = ({ endPoint = "", method = "GET", options = {} }) => { const [data, setData] = useState([]); const [request, setRequest] = useState<AxiosRequestConfig> ...

React - Incorrect use of hooks and class components

Understanding hooks as the opposite of a class component can be confusing. A simple line of code can trigger an error when trying to adapt it for use in a class component. Take, for example, this situation: .jsx files and functional components work seamles ...

I'm baffled by how the community response is implemented in this particular TypeScript exercise on Exercism

I am currently learning TypeScript from scratch by working on exercises available on exercism Successfully completed the 5th exercise on Pangram. Below is my solution: class Pangram { alphabet = "abcdefghijklmnopqrstuvwxyz" constructor(privat ...

Having difficulty retrieving values while using async-await

Utilizing the code below has been successful for me. I managed to retrieve the data in the spread (then), returning a http200 response. Promise.all([ axios({ method: 'post', url: 'https://oauth2.-arch.mand.com/oauth2/token&a ...

Firebase: No user record exists for this identifier. It is possible that the user has been removed from the system

Utilizing Ionic2/Angular2 along with AngularFire2 and Firebase for user authentication during login. Upon successful registration of a user using email & password, I am able to log in with that same email & password without any issues. public fireAuth: ...

Generating GraphQL Apollo types in React Native

I am currently using: Neo4J version 4.2 Apollo server GraphQL and @neo4j/graphql (to auto-generate Neo4J types from schema.graphql) Expo React Native with Apollo Client TypeScript I wanted to create TypeScript types for my GraphQL queries by following th ...

What is the best way to store an audio Blob in the repository file system?

Currently, I have set up a system to record user audio through the device's microphone and can successfully download it on the same device. However, my goal now is to store this audio in my database by making an API call. How can I efficiently send th ...

EventManager gathering of various subscriptions

Is it possible for JhiEventManager to handle multiple subscriptions, or do I need a separate subscription for each event? Will the destroy() method of JhiEventManager handle multiple subscriptions as well? export class SomeComponent implements OnInit, OnDe ...

Union template literal types are preprended in Typescript

Is there a method to generate specific string types from existing string types with a designated prefix? It's better to acknowledge that it doesn't exist than to dwell on this concept. type UserField = "id" | "name"; type Post ...

Navigating a vast JSON dataset containing identical key names: A step-by-step guide

I am faced with a massive json file that has the following format: name: 'xxx', worth: [123, 456, 789] children: [ {name: 'xxx', worth: [987, 654, 321], children: [ {name: 'xxx', ...

The Angular6 application is experiencing an issue where the JWT token is not being transmitted through

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { let request = req.clone({ setHeaders: this.getRequestHeaders() }); return next.handle(request).map((event: HttpEvent< ...

Having trouble decoding a cookie received from a React.js front-end on an Express server

When using React js for my front end, I decided to set a cookie using the react-cookie package. After confirming that the request cookie is successfully being set, I moved on to configure the Express server with the cookie parser middleware. app.use(cookie ...