我没有使用以下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>
答案 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';
});
我已采取以下步骤:
将代码移动到subscribe()内部。可观察的代码(在这种情况下为http请求)返回值之后,应在此处运行代码。
将循环压缩为单个映射函数。您原来的for
循环是不必要的,并且每次都对this.selspecialization
进行不必要的分配。