繁体   English   中英

在 ANGULAR 中使用 Typescript 的错误属性 _id

[英]Error property _id using Typescript in ANGULAR

我在 angular 中有此消息错误:

src/app/components/employee/employee.component.html:67:92 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.

67 <button class="btn btn-danger btn-sm mr-2 (click)="deleteEmployee(employee._id)">
                                                                                              

  src/app/components/employee/employee.component.ts:8:16
    8   templateUrl: './employee.component.html',
组件EmployeeComponent的模板出现错误

在此处输入图像描述

Model: Employee

在此处输入图像描述

服务:

在此处输入图像描述

JavaScript Function:

在此处输入图像描述

请需要知道为什么会这样

我认为为_id传入的值是“未初始化的”,因此它的值是未定义的。 如果没有看到更多您的代码,我无法判断。 解决此问题的一种方法是在您实例化员工时,确保_id实际上被设置为一个值,否则将其设置为'' (空白字符串)并检查它在您的 delete() 中是否有值。

另一种选择是编辑您的删除 function

deleteEmployee(_id: string | undefined){
     if(_id) { //Checks if the passed variable has a value
          ...
     } 
     else {
          // Error
     }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM