Search code examples
angularangular-httpclientangular14

How do I properly pass headers to each HTTP call in my Angular service?


I'm using Angular 14. I have created the below service:

import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HolidayCalendarService {
    ...
  private readonly headers: HttpHeaders;

  constructor(private httpClient: HttpClient,
    private configService: ConfigService,
    ...
  ) {    
    this.headers = new HttpHeaders({ 'appId': this.configService.config.appId});
  }

  add(obj: MyObject){
    return this.httpClient.post<MyResponse>(this.httpService.add(),myObj, {
        this.headers }).pipe(map((res: any) => res.data));
  }

I have a number of HTTP calls in the service, and for this reason I made headers a private property of the service. However, every time I reference this.headers in a method, I get this compilation error:

No overload matches this call.
  Overload 1 of 15, '(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; observe: "events"; context?: HttpContext | undefined; params?: HttpParams | ... 1 more ... | undefined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }): Observable<...>', gave the following error.
    Argument of type '{ this: any; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; observe: "events"; context?: HttpContext | undefined; params?: HttpParams | { ...; } | undefined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }'.

I'm not quite sure what this means, especially because when I rewrite the method like this:

  add(obj: MyObject){
    const headers = new HttpHeaders({ 'appId': this.configService.config.appId});
    return this.httpClient.post<MyResponse>(this.httpService.add(),myObj, {
        headers }).pipe(map((res: any) => res.data));
  }

everyting compiles.


Solution

  • What ended up working was

      add(obj: MyObject){
        const headers = new HttpHeaders({ 'appId': this.configService.config.appId});
        return this.httpClient.post<MyResponse>(this.httpService.add(),myObj, {
            headers: this.headers }).pipe(map((res: any) => res.data));
      }
    

    Not sure why the route of defining a const worked but here we are.