简体   繁体   中英

Error property _id using Typescript in ANGULAR

I have this message Error in 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',
Error occurs in the template of component EmployeeComponent

在此处输入图像描述

Model: Employee

在此处输入图像描述

Service:

在此处输入图像描述

JavaScript Function:

在此处输入图像描述

Please a need know why this happened

I think the value being passed in for _id is "uninitialized" and therefore its value is undefined. I can't tell without seeing more of your code. One way to fix this would be when you instantiate the employee, make sure _id is actually being set to a value, otherwise set it to '' (blank string) and check that it has a value or not in your delete().

Another option would be to edit your delete function

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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