I recently delved into learning Angular2 and Asp.net core, but I encountered an issue when trying to post an object. Here is the relevant code snippet:
Service.ts
file:
export class SubCategoryService {
//private headers: Headers;
constructor(private http: Http) {
//this.headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
// this.headers.append('Content-Type', 'application/json');
// this.headers.append('Accept', 'application/json');
}
public createItem = (subCategory: SubCategory): Observable<SubCategory> =>
{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let toAdd = JSON.stringify(subCategory);
return this.http.post("api/subcategory", toAdd, { headers: headers }).map((response: Response) => <SubCategory>response.json()).catch(this.handleError);
}
}
Component.ts
file:
export class SubCategoryComponent {
constructor(private service: SubCategoryService) { }
subCategories: SubCategory[];
SubCategory: SubCategory = new SubCategory();
onPost() {
this.service.createItem(this.SubCategory).subscribe(
subCategory => this.subCategories.push(subCategory),
error => console.log(error),
() => console.log('Get all items completed'));
this.isLoading = true;
}
}
When it comes to the Asp.Net Core Controller
:
[HttpPost]
public async Task<JsonResult> Post(SubCategory subCategory)
{
return new JsonResult("");
}
The controller seems to be hit with an empty object... Any help would be greatly appreciated.
I also tried using Postman to make the POST request and it worked fine. Could there be an issue with the information in the body?
Here's a screenshot of it working correctly: