0

我正在尝试从集合中删除员工,但它抛出了这个错误

错误

错误:src/app/components/employee/employee.component.html:72:68 - 错误 TS2345:类型为“字符串”的参数 | undefined' 不能分配给'string' 类型的参数。类型“未定义”不可分配给类型“字符串”。

72 <button class="btn btn-danger" (click)="deleteEmployee(employee._id)">

员工模型.ts

export interface Employee {
    name: string,
    office: string,
    position: string,
    salary: number,
    createdAt?: string,
    updatedAt?: string,
    _id?: string
}

员工组件.ts

deleteEmployee(_id: string){
    if (confirm('Are you sure you want to delete it?')){
      this.employeeService.deleteEmployee(_id).subscribe({
        next: (res)=>{
          this.getEmployees();
        },
        error: (e)=> console.log(e)
      })
    }
  }

员工.component.html

<tbody>
        <tr *ngFor="let employee of employeeService.employees">
          <td>{{ employee.name }}</td>
          <td>{{ employee.position }}</td>
          <td>{{ employee.office }}</td>
          <td>{{ employee.salary }}</td>
          <td>
            <button class="btn btn-secondary mr-2">
              <i class="material-icons">edit</i>
            </button>
            <button class="btn btn-danger" (click)="deleteEmployee(employee._id)">
              <i class="material-icons">delete</i>
            </button>
          </td>
        </tr>
      </tbody>

员工服务.ts

deleteEmployee( _id: string){
    return this.http.delete(`${this.URL_API}/${_id}`)}

服务器端 - employees.controller.js

employeeCrtl.deleteEmployee = async (req, res) => {
    await Employee.findByIdAndDelete(req.params.id)
    res.json({status: 'Employee Deleted'})
}

员工.js


const employeeSchema = new Schema({
    name: {type: String, required: true},
    position: {type: String, required: true},
    office: {type: String, required: true},
    salary: {type: Number, required: true},
}, {
    timestamps: true,
    versionKey: false
})

module.exports = model("Employee", employeeSchema);
4

1 回答 1

0

问题来自这里。当您声明id?时,这意味着id是一个可选变量并且具有类型 T | undefined

export interface Employee {
    ...
    _id?: string
}

要解决它,您必须从 中删除问号id

export interface Employee {
    ...
    _id: string
}
于 2022-01-07T06:11:15.570 回答