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

164
Views
Agregue el método de generación de encabezados al método de creación de rutas

Necesito un consejo sobre cómo mejorar mi código. Tengo una clase simple que obtiene datos del backend que usa autenticación de token jwt.

 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")}` }), }; };

Funciona bien, pero el problema comienza cuando obtengo muchos más métodos http. ¿Cómo puedo cambiar createCompleteRoute para no tener que usar generateHeaders() en cada método http? Pensé en hacer algo como:

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

entonces los métodos http podrían verse así:

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

Pero no tengo idea de cómo escribir una función válida.

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

0

La mejor manera de hacer lo que solicita podría ser llevar su lógica para crear encabezados a un interceptor , que agregará automáticamente los parámetros del encabezado a cada llamada http .

Podría ser algo como esto:

Su archivo de interceptor (es una especie de servicio, pero tiene que implementar 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 : más información sobre cómo agregar y actualizar encabezados y cómo usar el interceptor para interceptar solicitudes y respuestas:

Agregar y actualizar encabezados

Interceptar solicitudes y respuestas

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!