Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
Add generating headers method to route creating method

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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="\yourAPI\endpoint";
  
    //  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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!