简体   繁体   中英

http.post on Angular5

Angular 5 I am trying to build a function that create a resource on my API using Angular. On my employee.service.ts file I have a method called "saveEmployee" which is called by a function "addEmployee" which is on Employee.componenet.ts The function "addEmployee" is called when "Save Employee" button is pressed on HTML page. This is 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);
      });
}

And this is saveEmployee:

 saveEmployee(employee: Employee): Observable<Employee> {

let body = JSON.parse(JSON.stringify(employee));
return this.http.post(this.resourceUrl, body);
}

It is failing because of "invalid media type" because for some reason the JSON object pushed to the API has this look:

{  
  firstName:"arjan",
  lastName:"gjoni",
  fedexId:"7777",
  contractorId:20
}

If you notice this is not a valid JSON object because the property names are not in quotes.

I placed a console.log() on the saveEmployee function after Json.stringify() and the Jason object is valid in there. I also placed a console.log() on the addEmployee() function and there the JSON object is weird (like the one on the post). I also checked on console, the RequestPayload and in there the JSON object is not valid either.

I would appreciate any help. I am using Angular 5

Try passing the employee object as the second parameter of the this.http.post method instead of stringifying and parsing it into the body object.
Angular should be able to handle the native Javascript object and post it correctly to the server.

Try this:

let body = JSON.stringify(employee);
return this.http.post(this.resourceUrl, body);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM