簡體   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