html中的Angular 2模型(使用http post)

时间:2016-02-18 10:49:16

标签: http model typescript angular

我目前正在学习Angular 2,我将模型发布到后端时遇到问题。

这是函数的外观:

  addDepartment(department: Department){
      var headers = new Headers();
        headers["Access-Control-Allow-Origin"] = "http://localhost:65402";
        headers.append('Content-Type', 'application/json');

     return  this.http.post('http://localhost:65402/company/api/department'+ "/", JSON.stringify(department))
        .subscribe(res => {
          this.departments = res.json();
        });

这是html:

<div [hidden]="!showAddView" align="center">

    <div>
        <label for="editTitle">Department No:</label><br>
        <input #departmentNo placeholder="id">
    </div>
    <div>
        <label for="editAbrv">Department name:</label><br>
        <input #departmentName placeholder="name">
    </div>
    <div>
        <label for="editAbrv">Department Location:</label><br>
        <input #departmentLocation placeholder="location">
    </div>

    <div>
        <a href="javascript:void(0);" (click)="addDepartment(department)" title="Add">
            Save
        </a>
        <a href="javascript:void(0);" (click)=showHide() >
            Cancel
        </a>
    </div>
</div>

完整代码在此处:plunker

我不知道如何将整个模型发布到后端。它说我的addDepartment方法中的department = undefined。谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

您的代码存在一些问题:

  • 您正在呼叫(click)="addDepartment(department)",此department在任何地方都不存在。您可以将包含输入的div更改为form并从中获取值:

    <form  #f="ngForm" [hidden]="!showAddView" align="center">
      ....
      <a href="javascript:void(0);" (click)="addDepartment(f.value)" title="Add">
      ....
    </form>
    
  • 您没有使用自己创建的Headers。将它们添加到post()请求中:

    this.http.post('~', JSON.stringify(department), { headers: headers })`
    
  • 此外,您可能不需要"Access-Control-Allow-Origin",这些应该在您的服务器上。

答案 1 :(得分:0)

我不知道你的departement来自哪里。我会重构您的代码以利用ngModel,如下所述:

<div [hidden]="!showAddView" align="center">
  <div>
    <label for="editTitle">Department No:</label><br>
    <input [(ngModel)]="departement.departmentNo" placeholder="id">
  </div>
  <div>
    <label for="editAbrv">Department name:</label><br>
    <input [(ngModel)]="departement.departmentName" placehlder="name">
  </div>
  <div>
    <label for="editAbrv">Department Location:</label><br>
    <input [(ngModel)]="departement.departmentLocation" placeholder="location">
  </div>

  <div>
    <a href="javascript:void(0);" (click)="addDepartment(department)" title="Add">
      Save
    </a>
    <a href="javascript:void(0);" (click)=showHide() >
      Cancel
    </a>
  </div>
</div>

您应该使用空对象初始化此属性:

contructor() {
  this.department = {};
}

关于标题,没有什么可以发送给CORS。浏览器将自动发送包含执行请求的应用程序域的Origin标头。服务器将检测它,如果它支持CORS,将发回相应的头(包括Access-Control-Allow-Origin一个)。这个链接可以给出关于CORS的提示:

正如Saxsa强调的那样,您忘记在您的请求中使用headers ...