繁体   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