Angular 2 HTTP post Web API 2始终收到空

时间:2017-08-20 13:35:03

标签: c# angular asp.net-web-api

user.service.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';

import * as myGlobal from '../global';

@Injectable()
export class UserService {

constructor(private http: Http) {}

postUser(user:any[]) {
  let headers = new Headers({ 'Content-Type': 'application/x-www-form-
  urlencoded; charset=UTF-8', 'Accept' : 'application/json' });
  return this.http.post(myGlobal.myUrl + 'user/insert', JSON.stringify(user)
  , {headers: headers});
  }
}

user.component.ts

submitForm(data: any):void{
  console.log(data);
  this._service.postUser(data)
  .subscribe(
  (response) => console.log(response),
  (error) => console.log(error)
  );
}

Web API

[HttpPost]
[Route("api/user/insert")]
public HttpResponseMessage insertVehiclesDevice(modelUser data)
{
  //stuff
  return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}

当我调用方法Insert时,数据总是以零或零的形式到达, 我必须更改{ 'Accept' : 'application/json' }的{​​{1}}行,因为它给了我405错误

提前感谢所有人

2 个答案:

答案 0 :(得分:1)

问题出在这里:

componentDidMount

将其更改为:

return this.http.post(myGlobal.myUrl + 'user/insert' 
     , JSON.stringify(user)
     , {headers: headers});

错误处理程序:

return this.http.post(myGlobal.myUrl + 'user/insert' 
     , JSON.stringify(user)
     , {headers: headers})
   .map(    (response: Response) =>response.json())
   .catch(this._errorHandler);

您需要一些导入:

_errorHandler(error:Response){
  console.log(error);
  return Observable.throw(error || "Internal server error");
}

答案 1 :(得分:0)

将输入值更改为user,传递的data's name和接受的参数必须具有相同的名称。在postUser中,您的数据名称为user。也可以在API中使用相同的内容。

[HttpPost]
[Route("api/user/insert")]
public HttpResponseMessage insertVehiclesDevice(modelUser user)
{
  //stuff
  return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}