简体   繁体   中英

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

I have not got any values from an array using the following TS code:

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';   
}

My HTML code is:

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

It's hard to tell whether this is meant to be one block of code due to the mismatching variable / property names. My guess is that you're trying to process the results of the http request outside of the observable - before the data service has returned the data.

What happens if you try the following:

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';
});

I've taken the following steps:

  1. Move code to inside the subscribe(). This is where code should run after the observable (http request in this case) returns a value.

  2. Compress your loop into a single map function. Your original for loop was unecessary and also performing an unecessary assignment to this.selspecialization each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM