Home > Blockchain >  How doI I properly pass HttpHeaders to each http call in my Angular service?
How doI I properly pass HttpHeaders to each http call in my Angular service?

Time:12-08

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 variable 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.

CodePudding user response:

From what I can see I could say that it is a problem with obj: MyObject that receives the add() function, I think you should check the structure that has that object.

CodePudding user response:

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.

  • Related