从角度为4的{HttpClient.post}

时间:2018-01-17 02:35:25

标签: angular http-post asp.net-web-api2 angular2-services

我遇到问题是将数据从我的角度2应用程序发布到我的web api。我是angular 2的新手,因为当我将数据发布到Web API并在Web API中放置调试器时,请求到达但所有值都保持为null。我在最近2天打败了我的脑袋,仍然无法找到错误,为什么我没有在Web API中获取对象的值。

来自Web API的代码:

[HttpPost]
[Route("PostEmployee")]
[ResponseType(typeof(Employee))]
public IHttpActionResult PostEmployee(Employee employee)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.Employees.Add(employee);
    db.SaveChanges();

    return Ok(employee);
    //return CreatedAtRoute("DefaultApi", new { id = employee.Id }, employee);
}

来自Web Api的模型:

public partial class Employee
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public string ContactPreference { get; set; }
    public string Gender { get; set; }
    public int DepartmentId { get; set; }
    public Nullable<System.DateTime> DateOfBirth { get; set; }
    public string Photo { get; set; }
    public bool IsActive { get; set; }
    public virtual Department Department { get; set; }
}

TypeScript中的模型

export class Employee 
{
    Id : number;
    FullName: string;
    Email: string;
    PhoneNumber: string;
    ContactPreference: string;
    Gender: string;   
    DepartmentId: number;
    DateOfBirth?: Date;
    Photo:string;
    isActive: boolean;
}

来自我的Angular 2应用程序employee.service.ts

的代码
 createEmployee(employee: Employee) {
    let _headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' });
    let options = new RequestOptions({ headers: _headers });
    let body = JSON.stringify(employee);

    return this._http.post(API_URL + '/api/Employees/PostEmployee', body, options)
        .map((res: Response) => res.json())
        .catch(this.handleError);
}

handleError(error: Response) {
    console.error(error);
    return Observable.throw(error);
}

我在调试器模式下附加Web API的图像将捕获请求 enter image description here

请在此解决方案中帮助我。感谢。

0 个答案:

没有答案