javascript - 我无法访问两个对象中的 id

标签 javascript html angular typescript

我是 Angular 的新手,我无法在 Position 和 Department 中发布 id 的值,出于某种原因,它无法访问 id

addEmployee.model.ts

export class AddEmployee {

  Position: {
    id: string;
  };
  Department: {
    id: string;
  };
}

添加员工服务

DefineEmployee(addEmployee: AddEmployee) {
  const body: AddEmployee = {

    Position: {
      id: addEmployee.Position.id
    },

    Department: {
      id: addEmployee.Department.id
    }
  }
  return this.http.post('url', body);
}

AddEmployee.component.ts

onSubmit(form: NgForm) {

  return this.restService.DefineEmployee(form.value).subscribe((res: any) => {
    this.resetForm(form);
    console.log(res);
  }, error => {
    this.resetForm(form);
  })
}

addEmployee.component.html

<div class="form-group">

  //AddEmployee.Position.id comes up with undefined element 'id'

  <select [(ngModel)]="AddEmployee.Position.id" name="Position" Position="ngModel" class="form- 
             control customized-dropdown">
    <option [value]="item.id" *ngFor="let item of positions">{{item.name_FL}}</option>
  </select>
</div>

最佳答案

由于错误来自服务 AddEmployeeService,我相信对该服务的调用没有传递您的函数期望的参数。

当您调用 this.restService.DefineEmployee(form.value) 时,我相信 value 属性没有 Position部门属性。

您可以按照指示添加调试器来测试它:

DefineEmployee(addEmployee: AddEmployee) {
  console.log(addEmployee);
  debugger;
  const body: AddEmployee = {

    Position: {
      id: addEmployee.Position.id
    },
    ...

这应该可以帮助您修复该功能

更新

Op 将 addEmployee 变量的内容发布为:

{
 "Position":"c8a06de6-58e1-439a6fc-08d7553139ac",
 "Department":"552ccb91-02f8-476b-adbc-08d7553136bf"
}

职位和部门的 ID 似乎在“addEmployee”变量中没有“id”属性;

所以要解决这个问题,只需从服务中的 addEmployee 中删除“ids”

DefineEmployee(addEmployee: AddEmployee) {
  const body: AddEmployee = {

    Position: {
      id: addEmployee.Position // <<< here
    },

    Department: {
      id: addEmployee.Department  // <<< here
    }
  }
  return this.http.post('url', body);
}

关于javascript - 我无法访问两个对象中的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58472414/

相关文章:

java - 如何将参数从 cordova HTTP 传递到 Spring Controller

javascript - 无法让我的页面正常工作

javascript - 选中和取消选中复选框

javascript - Javascript 中表格上的“保存”按钮不起作用

javascript - 添加禁用提交按钮的 javascript 时,客户端验证消息不显示

javascript - 在另一个 div 中移动一个 div

javascript - 如何每秒向 var 添加一个数字

angular - 类型 'Observable<{}> is not assignable to type ' 可观察'

angular - 验证复选框列表 Angular 2

javascript - 如何删除plotly.js中的轴悬停信息?