Angular 5 Attempting to create a function that will generate a resource on my API using Angular has proven to be a challenge. The "employee.service.ts" file contains a method named "saveEmployee" which is triggered by a function called "addEmployee" located in the Employee.component.ts file. This particular function is executed when the "Save Employee" button is clicked on the HTML page. Here is the implementation of the addEmployee function:
addEmployee(model) {
this.loading = true;
model.contractorId = parseInt(model.contractorId);
this.employeeService.saveEmployee(model)
.subscribe(
data => {
console.log('saved successfully!!!');
return true;
},
error => {
console.error("Error creating employee!");
return Observable.throw(error);
});
}
Now, let's take a look at the saveEmployee method:
saveEmployee(employee: Employee): Observable<Employee> {
let body = JSON.parse(JSON.stringify(employee));
return this.http.post(this.resourceUrl, body);
}
The process fails due to an "invalid media type" issue arising from the fact that the JSON object being sent to the API does not adhere to the correct format:
{
firstName:"arjan",
lastName:"gjoni",
fedexId:"7777",
contractorId:20
}
This can be attributed to the absence of quotes around the property names, rendering it invalid as a JSON object.
I placed a console.log() inside the saveEmployee function right after Json.stringify(). It confirmed that the transformed JSON object is valid at that point. However, upon checking the addEmployee() function, the JSON object appears distorted (similar to the one sent during the POST request). Furthermore, inspecting the RequestPayload in the console reveals that the JSON object is invalid there as well.
If anyone could offer guidance on resolving this issue, it would be greatly appreciated. Thank you for your assistance. Running Angular 5.