TypeError:无法读取角度6中未定义的属性“ length”

时间:2020-02-13 06:02:05

标签: angular typescript

我没有使用以下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>

1 个答案:

答案 0 :(得分:2)

由于变量/属性名称不匹配,很难说这是否是一个代码块。我的猜测是,您正在尝试在可观察对象之外处理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()内部。可观察的代码(在这种情况下为http请求)返回值之后,应在此处运行代码。

  2. 将循环压缩为单个映射函数。您原来的for循环是不必要的,并且每次都对this.selspecialization进行不必要的分配。