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

128
Views
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 answers
Answer question

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 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!