Angular2/4 post method not working

2019-09-01 16:16发布

问题:

I am new in angular2/ 4 web api. I want to save some data to database using angular 4 web api http. When i call a GET method from angular it works fine, but not working on POST method. I am getting 415 Unsupported Media Type.All the time, but when I use postman the post method is work fine because I change the content type to application/json. when i use alert button i get [object,Object],But in angular2/4 it's not working... I see lots of issues with the same problem, but they don't work for me.

This is my service.ts file

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

This is my component.ts file

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

This is my api code

 [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; }

    }

This is my error

"{"Message":"The request entity's media type 'text/plain' is not supported for this resource.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type

回答1:

Your api is expecting an array but you send a string instead, that is why you get a status code of 415

And remove the param, it is not even required in your 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);
}

About the error you're encountering, look at your api, you're not even returning a data, which why on map you get an error, remove the map will solve your issue for now.

You have to update your component

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


回答2:

Try using below code:

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


回答3:

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

Noticed you are using the deprecated version of HTTP, from @angular/http. You should consider changing it to use HttpClient instead from @angular/common/http see: https://angular.io/api/common/http/HttpClient