簡體   English   中英

類型錯誤:無法讀取角度 6 中未定義的屬性“長度”

[英]TypeError: Cannot read property 'length' of undefined in angular 6

我沒有使用以下 TS 代碼從數組中獲得任何值:

this.dataservice.get("common/public/getAllCategories", null).subscribe(data => {
      //  //console.log('categories'+JSON.stringify( data));
   this.categoriesarray = data;
});
var data = this.items;
var categoriesdata = [];
for (var i = 0; i < data['categories'].length; i++) { // <- Error comes on this line
    categoriesdata.push(data['categories'][i].categoryID);
    this.selspecialization = categoriesdata;
}
this.EditRequest = 'block';   
}

我的 HTML 代碼是:

<button type="button" *ngIf="!userRechargeTable" class=" smallbtns btn roundButton btn-theme blue" (click)="edit()"> 
 Edit
</button>

由於變量/屬性名稱不匹配,很難判斷這是否是一個代碼塊。 我的猜測是您正在嘗試在 observable 之外處理 http 請求的結果 - 在數據服務返回數據之前。

如果您嘗試以下操作,會發生什么情況:

this.dataservice.get("common/public/getAllCategories", null).subscribe(data => {
  //  //console.log('categories'+JSON.stringify( data));
  this.categoriesarray = data;
  // this has been moved inside the observable, and also optimised using the map function
  this.selspecialization = data['categories'].map(x => x.categoryID);
  this.EditRequest = 'block';
});

我采取了以下步驟:

  1. 將代碼移動到 subscribe() 內部。 這是在 observable(在這種情況下為 http 請求)返回值后代碼應該運行的地方。

  2. 將您的循環壓縮為單個 map 函數。 您原來的for循環是不必要的,並且每次都對this.selspecialization執行不必要的分配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM