Reputation: 945
Routes code below:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
Controller code below :
// POST api/values
[HttpPost]
public void Post([FromBody]Employee employee)
{
employeeManager.CreateAsync(employee);
}
All other methods working except the post method.
call from angular component :
onSubmit(employeeItems: any) {
console.log(employeeItems);
this.getData();
var headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
this.http.post('api/Employee/Post', employeeItems, { headers: headers }).subscribe();
this.createEmployeeFlag = false;
}
I tried even from Postman, but no luck.
Upvotes: 4
Views: 6482
Reputation: 4838
This is the code that you would need in your service, there are two issues here, first is the URL, it needs to be the complete URL path. The second is is that you are trying to subscribe to something before mapping it to a Observable
onSubmit(employeeItems: any) {
let url: string = 'http://localhost/api/employee'; //this will be the complete url that you would hit with say postman
this.getData(); //I'm not sure what this is so I'm leaving it here
this.http.post(url, employeeItems)
.map((response: Response) => response.json())
.Subscribe((response: any) => {
//do whatever with the response here.
});
this.createEmployeeFlag = false;
}
I would suggest breaking this up into a *.service.ts
file.
*.service.ts
public postEmployee(employeeItems: any): Observable<any> {
let url: string = 'http://localhost/api/employee'; //this will be the complete url that you would hit with say postman
this.http.post(url, employeeItems)
.map((response: Response) => response.json());
}
inside your *.component.ts
constructor(private service: Service) {}
onSubmit(employeeItems: any) {
this.getData(); //I'm not sure what this is so I'm leaving it here
this.service.postEmployee(employeeItems)
.Subscribe((response: any) => {
//do whatever with the response here.
});
this.createEmployeeFlag = false;
}
Upvotes: 1
Reputation: 247088
Your url and route templates do not match
[Route("api/[controller]")]
public class EmployeeController : Controller {
[HttpPost]
public async Task<IActionResult> Post([FromBody]Employee employee) {
await employeeManager.CreateAsync(employee);
return Ok();
}
}
and update your calling URL to call the default endpoint api/Employee
onSubmit(employeeItems: any) {
console.log(employeeItems);
this.getData();
var headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
this.http.post('api/Employee', employeeItems, { headers: headers }).subscribe();
this.createEmployeeFlag = false;
}
Upvotes: 4