Angular2 / 4 post方法不起作用

时间:2018-05-29 04:49:18

标签: angular asp.net-web-api angular2-services angular4-forms angular4-httpclient

我是angular2 / 4 web api的新手。我想使用angular 4 web api http将一些数据保存到数据库。当我从angular调用GET方法时,它工作正常,但不适用于POST方法。我得到415不支持的媒体类型。所有的时间,但当我使用postman时post方法工作正常,因为我将内容类型更改为application / json。当我使用警报按钮时,我得到[对象,对象],但在angular2 / 4中它不起作用......我看到很多问题出现同样的问题,但它们对我不起作用。

这是我的service.ts文件

 CatchStockDetail(stock: any)
    : Observable<IStockdetails[]> {
    alert(stock);      

          let stockdetail = JSON.stringify([{ stock }]);
     let headers = new Headers({ 'Content-Type': 'application/json' });
     let options = new RequestOptions({ headers: headers });
    return this._http.post('http://localhost:1234/api/NewStockCount/' + 'Stock', stockdetail,
        { params: [{ stock }] })
        //  .map(res => res.json());
        //     .map(res => res.json().stock)
        .map((response: Response) => <IStockdetails[]>response.json())
        .catch(this.handleError);
}

这是我的component.ts文件

 this._enqService.CatchStockDetail(this.stock)
            .subscribe(value => {
                value.forEach(stock => {
                    this.stockdetail.push(this.stock)
                });
            },
                error => {
                    console.error(error);
                    this.statusMessage = "Problem with the service.Please try again after sometime";
                });

这是我的api代码

 [HttpPost]
    public void Stock([FromBody] List<spGetNewStockCountDetails_Result> jsonvalues)

    {
        foreach (spGetNewStockCountDetails_Result Datastock in jsonvalues)
        {
            spGetNewStockCountDetails_Result Stockobject = new spGetNewStockCountDetails_Result();
            Stockobject.schid = Datastock.schid;
            Stockobject.itemid = Datastock.itemid;
            Stockobject.itemcode = Datastock.itemcode;
            Stockobject.itemdescription = Datastock.itemdescription;
            Stockobject.packingtypeid = Datastock.packingtypeid;
            Stockobject.count = Datastock.count;

            enqentities.spGetNewStockCountDetails(Datastock.schid, Datastock.itemid, Datastock.itemcode, Datastock.itemdescription, Datastock.packingtypeid, Datastock.count);
        }

    }

    public class spGetNewStockCountDetails
    {

        public int schid { get; set; }
        // public int id { get; set; }
        public int itemid { get; set; }
        public string itemcode { get; set; }
        public string itemdescription { get; set; }
        public int packingtypeid { get; set; }
        public int count { get; set; }

    }

这是我的错误

“{”Message“:”此资源不支持请求实体的媒体类型'text / plain'。“,”ExceptionMessage“:”没有MediaTypeFormatter可用于读取类型

的对象

3 个答案:

答案 0 :(得分:0)

您的api期待数组,但您发送字符串,这就是您获得状态代码415

的原因

删除参数,你的api甚至不需要它。

CatchStockDetail(stock: any)
    : Observable<IStockdetails[]> {
    alert(stock);      

     let stockdetail = stock;
     let headers = new Headers({ 'Content-Type': 'application/json' });
     let options = new RequestOptions({ headers: headers });
     return this._http.post('http://localhost:1234/api/NewStockCount/' + 'Stock', stockdetail, options)
        .map((response: Response) => <IStockdetails[]>response.json())
        .catch(this.handleError);
}

关于您遇到的错误,请查看您的API,您甚至没有返回数据,这就是map您收到错误的原因,删除map将解决您的问题现在

您必须更新组件

this._enqService.CatchStockDetail(this.stock)
            .subscribe(value => {
if(typeof value !== 'undefined' && value != null){
         value.forEach(stock => {
              this.stockdetail.push(this.stock)
         });
     }
},
error => {
         console.error(error);
         this.statusMessage = "Problem with the service.Please try again after sometime";
});

答案 1 :(得分:0)

尝试使用以下代码:

 CatchStockDetail(stock: any): Observable<IStockdetails[]> {
    let body = JSON.stringify([stock]);
    let url = 'http://localhost:1234/api/NewStockCount/' + 'Stock';
    let head: Headers = new Headers();
    head.set('Content-Type', 'application/json');
    head.set('Accept', 'application/json');

    return this._http.post(url, body, head)
      .map((response: Response) => response.json())
      .catch(this.handleError);
  }

答案 2 :(得分:-1)

CatchStockDetail(stock: any): Observable<IStockdetails[]> {   

    let stockdetail = JSON.stringify([{ stock }]);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers, params: [{ stock }]  });

    return this._http.post('http://localhost:1234/api/NewStockCount/' + 'Stock', stockdetail, options)
    .map((response: Response) => <IStockdetails[]>response.json())
    .catch(this.handleError);
}

注意到您使用的是@angular/http中已弃用的HTTP版本。您应该考虑将其更改为使用HttpClient而不是@angular/common/http,请参阅:https://angular.io/api/common/http/HttpClient