2017-01-16 85 views
2

我正在構建一個帶有angular2前端和.NET後端的站點,對後端的GET調用一直在完美地工作。從angular2到.NET web api的HTTP發佈不起作用

現在我想發佈一些東西到我的服務器,但我似乎無法得到它的工作。

角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')); 
} 

角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)); 
} 

端點對應,模型對應。

調用正在進行中,我在控制器的開始處放置了一個斷點,以查看它是否進入,但是我沒有。我錯過了什麼嗎?

謝謝!

編輯:

方法獲取的卡列斯在這裏:

@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> 
+0

你在哪裏訂閱'postCategory'? – echonax

+0

postCategory get從我的一個組件中調用。已經測試過正在進行POST調用。 – TanguyB

+0

請在你的問題中分享你的代碼。你是如何測試它的?你能否也包括迴應? – echonax

回答

2

觀測量不會讓一個請求,除非你subscribe他們因此你沒有進行後端通話。

你應該subsribe它是這樣的:

this.categoryService.postCategory(new Category(this.name, this.parent, null)).subscribe((response)=>{ 
    console.log(response); 
}); 
+0

我現在會測試它。 – TanguyB

+0

謝謝你是老闆! – TanguyB

+0

@TanguyB哈哈,很高興我能幫上忙。 – echonax