Well, as for what’s going on with the 415 error, you’d have to ask whoever administers wherever you’re posting it to, but I can say this: there is no need for manually calling JSON.stringify
or making customHttpHeaders
, and I think it’s a very important thing to never do unnecessary stuff for two major reasons:
- it distracts from the important part of your code, making it harder to read;
- it’s easy to inadvertently mess things up;
HttpClient
is smarter than you give it credit for.
this.http.post<ReturnType>(url, data)
works just fine.
Finally, this service adds no value as written. The point of services like this is to abstract something away. I try to make it so that client code only sees business level objects, so I want something like:
interface Customer {
id: string;
name: string;
...
}
class CustomerService {
constructor(private http: HttpClient) {}
allCustomers(): Observable<Customer[]> {
return this.http.get<Customer[]>("/api/customers");
}
customerById(id: string): Observable<Customer> {
return this.http.get<Customer>(`/api/customer/${id}`);
}
updateCustomer(cust: Customer): Observable<Customer> {
return this.http.post<Customer>(`/api/customer/${id}`, cust);
}
}
The point here is that as far as outside this class is concerned, there is just a magical source of Customer
s. We don’t know that they’re coming over HTTP, we don’t care what methods are being used. Maybe there is an offline mode where these things come from on-device storage. Maybe it’s all mocked out and we’re getting fake data for testing. It is very important that all those sorts of changes can be made by only editing CustomerService
. No clients of that class ever need to be affected.