简体   繁体   English

Angular5上的http.post

[英]http.post on Angular5

Angular 5 I am trying to build a function that create a resource on my API using Angular. Angular 5我正在尝试构建一个函数,该函数使用Angular在我的API上创建资源。 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. 在我的employee.service.ts文件中,我有一个名为“ saveEmployee”的方法,该方法由Employee.componenet.ts上的函数“ addEmployee”调用。页。 This is addEmployee function: 这是addEmployee函数:

 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:

 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: 由于“无效的媒体类型”而失败,因为由于某种原因,推送到API的JSON对象具有以下外观:

{  
  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. 如果您注意到这不是有效的JSON对象,因为属性名称不在引号中。

I placed a console.log() on the saveEmployee function after Json.stringify() and the Jason object is valid in there. 我将console.log()放在Json.stringify()之后的saveEmployee函数上,并且Jason对象在其中有效。 I also placed a console.log() on the addEmployee() function and there the JSON object is weird (like the one on the post). 我还在addEmployee()函数上放置了console.log(),并且JSON对象很奇怪(就像文章中的那个一样)。 I also checked on console, the RequestPayload and in there the JSON object is not valid either. 我还在控制台上检查了RequestPayload,其中的JSON对象也无效。

I would appreciate any help. 我将不胜感激任何帮助。 I am using Angular 5 我正在使用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. 尝试将employee对象作为this.http.post方法的第二个参数传递,而不是将其字符串化并解析为body对象。
Angular should be able to handle the native Javascript object and post it correctly to the server. Angular应该能够处理本机Javascript对象并将其正确发布到服务器。

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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