0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I can't use this solution because I'm already attaching another header in the current interceptor
Isn't it possible to set multiple headers in one interceptor? Otherwise have you tried out chaining interceptors?
You can have as many interceptors as you want..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.