Skip to content
Advertisement

Add generating headers method to route creating method [closed]

I need an advice how to make my code better. I have a simple class that gets data from backend that is using jwt token auth.

export class RepositoryService {

  constructor(private http: HttpClient, private envUrl: EnvironmentUrlService) { }

  public getData = (route: string) => {
    return this.http.get(this.createCompleteRoute(route, this.envUrl.urlAddress), this.generateHeaders());
  }

 
  private createCompleteRoute = (route: string, envAddress: string) => {
    return `${envAddress}/${route}`;
  }
  private generateHeaders = () => {
    return {
      headers: new HttpHeaders({
        "Content-Type": "application/json",
        "Authorization": `Bearer ${localStorage.getItem("token")}`
        }),
    };
  }; 

It works fine but the problem starts when I get a lot more of http methods. How can I change createCompleteRoute so I won’t have to use generateHeaders() in every http method? I though about doing something like:

private createCompleteRoute = (route: string, envAddress: string) => {
    return `${envAddress}/${route}`, this.generateHeaders();
  }

so http methods could look like this:

public getData = (route: string) => {
    return this.http.get(this.createCompleteRoute(route, this.envUrl.urlAddress));
  }

But have no idea how to write a valid function.

Advertisement

Answer

The best way to do what you ask for, could be to bring your logic for creating headers to an interceptor, which is going to automatically add the header parameters to every http call.

It could be something like this:

Your interceptor file (is kinda service, but have to implement HttpInterceptor:

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
} from '@angular/common/http';

// The service/way you use to get your token
import { AuthService } from '../services/auth.service';

@Injectable()
export class MyInterceptor implements HttpInterceptor {

  constructor(private authService: AuthService) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
  
  const url="yourAPIendpoint";
  
    //  Get your token
    cont myToken = this.authService.getToken(); // or localStorage.getItem("token") or whatever your way to get your token
  
    
    // Add authorization header with token if available   
    if (myToken) {
    
       request = request.clone({
          setHeaders: {
            Authorization: `Bearer ${currentUser.user.api_token}`,
            'Content-Type': 'application/json',
          },
          url,
        });
        
    } 
    
    ...
    }

EXTRA: More info about how to adding and updating headers and how to Use the interceptor for Intercepting requests and responses:

Adding & Updating Headers

Intercepting request & responses

Advertisement