I have been working on a small Angular Application for educational purposes, where I am utilizing a .net core WebApi to interact with data.
One question that has come up involves the consistent use of headers in all Post and Put requests:
const headers = new HttpHeaders().set('content-type', 'application/json');
These headers are being added in a similar way for both post and put requests:
return this.http.post<SmartCard>(AppDefinitions.ApiSmartCardAdminPath, body, { headers })
To streamline this process, I decided to centralize the header definition in my AppDefinitions Class:
import { HttpHeaders } from "@angular/common/http";
export class AppDefinitions {
public static ApiBasePath: string = "http://<my webapp name>.azurewebsites.net/api/";
public static ApiLoginPath: string = AppDefinitions.ApiBasePath + "Login/";
public static ApiSmartCardAdminPath: string = AppDefinitions.ApiBasePath + "SmartCard/";
public static JsonHttpHeaders: HttpHeaders = new HttpHeaders().set('content-type', 'application/json');
}
Instead of adding headers directly in the individual methods, I attempted to call JsonHttpHeaders like this:
return this.http.post<SmartCard>(AppDefinitions.ApiSmartCardAdminPath, body, { this.GetHttpHeaders() })
However, this caused an error indicating a type mismatch. It seemed to suggest that AppDefinitions was returning any. To address this, I tried creating a method within the service class:
GetHttpHeaders() : HttpHeaders{
const headers = new HttpHeaders().set('content-type', 'application/json');
return headers;
}
Unfortunately, this approach also resulted in the same error message.
I'm puzzled about what I might be doing wrong in this situation. Any insights or suggestions would be greatly appreciated.