Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
Setting request Header in Angular post request method globally

I have the following method in an angular service which is working properly

 getMyRequests( userId: string){
    const headers = new HttpHeaders().set('Authorization', `Bearer ${localStorage.getItem(CONSTS.MIDDLEWARE_TOKEN)}`);
    return this.http.post<any>(this.MIDDLEWARE_MY_REQUESTS,{ "userId": userId  }, { headers , params: null })
  }

However the headers part is set locally in the method, and since it used multiple times in differnt methods within the same service I would like to set it in the service globally I tried the following but it doest work

export class MyService {
  
      headers = new HttpHeaders().set('Authorization', `Bearer ${localStorage.getItem(CONSTS.MIDDLEWARE_TOKEN)}`);
     getMyRequests( userId: string){
        return this.http.post<any>(this.MIDDLEWARE_MY_REQUESTS,{ "userId": userId  }, { this.headers , params: null })
      }

I would like to know what is the correct solution for this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In Angular you can use the HttpInterceptor interface for this. It provides the Method

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>

which takes your outgoing Request and modifies it the way you want to.

So what you need to do is:

  1. Create a new class which implements the HttpInterceptor interface
  2. Add the Authorization Header to the request inside the intercept method

Link to Angulars Documentation: https://angular.io/api/common/http/HttpInterceptor

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda