[英]HTTP Post from angular2 to .NET web api doesn't work
我正在構建一個帶有 angular2 前端和 .NET 后端的站點,對后端的 GET 調用一直工作得很好。
現在我想向我的服務器發布一些東西,但我似乎無法讓它工作。
Angular 2 服務方法
postCategory(category: Category){
let endpoint = this.url + 'add';
let body = JSON.stringify(category);
let options = new RequestOptions({headers: this.headers});
return this.http.post(endpoint, body, options)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server Error'));
}
Angular 2 DTO 模型
export class Category{
constructor(
public CategoryName: string,
public ParentId: number,
public ChildCategories: Category[]
){}
}
.NET DTO 模型
public class CategoryDTO
{
public string CategoryName { get; set; }
public int? ParentId { get; set; }
public IList<CategoryDTO> ChildCategories { get; set; }
public CategoryDTO(string name, int? parent, IList<CategoryDTO> child)
{
CategoryName = name;
ParentId = parent;
ChildCategories = child;
}
}
.NET WEB API 控制器
[HttpPost]
[Route("add")]
public IHttpActionResult PostCategory([FromBody]CategoryDTO category)
{
var newCategory = _categoryService.AddCategory(_dtoBuilder.CategoryDtoToCategory(category));
if(newCategory == null) return NotFound();
return Ok(_dtoBuilder.CategoryToDto(newCategory));
}
端點對應,模型對應。
正在進行調用,我在控制器的開頭放置了一個斷點,以查看它是否進入,但我沒有。 我錯過了什么嗎?
謝謝!
編輯:
方法 Get 在這里調用:
@Component({
moduleId: module.id,
selector: 'admin-category',
templateUrl: 'admin-category.component.html',
styleUrls: ['admin-category.component.css']
})
export class AdminCategoryComponent{
name: string;
parent: number;
constructor(
private categoryService: CategoryService
){}
addCategory(): void{
this.categoryService.postCategory(new Category(this.name, this.parent, null));
}
}
該組件的模板:
<h1>Add Category</h1>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" [(ngModel)]="name">
</div>
<div class="form-group">
<label for="parent">ParentId:</label>
<input type="text" class="form-control" id="parent" [(ngModel)]="parent">
</div>
<button class="btn btn-default" (click)="addCategory()">Submit</button>
除非您subscribe
Observables,否則不會發出請求,因此您不會進行后端調用。
你應該像這樣訂閱它:
this.categoryService.postCategory(new Category(this.name, this.parent, null)).subscribe((response)=>{
console.log(response);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.