使用Angular 2 http操作将数字传递给MVC控制器

时间:2017-02-07 09:24:33

标签: asp.net asp.net-mvc angular

我正在尝试将id从角度2传递到Asp.net mvc控制器,但收到错误Internal server Errror

我的组件代码是:

import { Component, OnInit, OnDestroy } from "@angular/core";
import { Products } from "../Models/products";
import { Http, Headers } from "@angular/http";
import { ActivatedRoute } from '@angular/router';

@Component({
    template: 'This Is Category {{id}}'
})
export class CategoryComponent implements OnInit, OnDestroy {
    private products: Products[];
    id: number;
    private sub: any;
    constructor(private http: Http, private route: ActivatedRoute) { }
    ngOnInit() {
        debugger;
        this.sub = this.route.params.subscribe(params => {
            this.id = +params['id']; // (+) converts string 'id' to a number
        });

        let headers = new Headers({ 'Content-Type': 'application/json' });
        this.http.post("/Products/GetProductByCategory", JSON.stringify(this.id), { headers: headers }).subscribe(data => {
            let body = data.text();
            debugger;
            this.products = JSON.parse(body);
        });
    }
    ngOnDestroy() {
        this.sub.unsubscribe();
    }
}

我的Asp网络控制器代码是:

   public JsonResult GetProductByCategory(int id)
        {
            List<ProductsModel> productList = new List<ProductsModel>();
            productList = productBl.GetProductByCategory(id);
            JavaScriptSerializer js = new JavaScriptSerializer();
            js.Serialize(productList);
            return Json(productList, JsonRequestBehavior.AllowGet);
        }

有谁能告诉我我的代码有什么问题。提前致谢

2 个答案:

答案 0 :(得分:2)

要摆脱异步问题,您可以将调用转移到订阅,但我不确定这是否会修复内部服务器错误:

ngOnInit() {
    debugger;
    this.sub = this.route.params.subscribe(params => {
        this.id = +params['id']; // (+) converts string 'id' to a number
        let headers = new Headers({ 'Content-Type': 'application/json' });
        this.http.post("/Products/GetProductByCategory", JSON.stringify(this.id), { headers: headers }).subscribe(data => {
           let body = data.text();
           debugger;
           this.products = JSON.parse(body);
       });
    }); 
}

答案 1 :(得分:1)

IMO这应该是关于HTTP的GET请求,id应该作为路由值或查询字符串传递。

this.http.get("/Products/GetProductByCategory?id="+this.id,...)