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

问题描述 投票:0回答:1

这是我的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>
angular typescript
1个回答
0
投票

由于变量/属性名称不匹配,很难说这是否是一个代码块。我的猜测是,您正在尝试在可观察对象之外处理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进行不必要的分配。

© www.soinside.com 2019 - 2024. All rights reserved.