Iterate through an array of objects Angular 2

ⅰ亾dé卋堺 提交于 2019-12-01 18:49:45

You have an asynchronous method here:

   this._fleetSummaryService.getFleetSummary()
             .subscribe(
                 fleetSummary => this.summary = fleetSummary,

                 error => this.errorMessage = <any>error)

and after this you are trying to iterate over it here:

for (var i = 0; i < this.summary.length; i++) {

Your code will be in the for loop before the response from your subscription arrives. Hence this.summary will be undefined.

If you want to iterate through the response when it arrives you should move your for loop inside the callback like this:

 this._fleetSummaryService.getFleetSummary()
             .subscribe(
                 (fleetSummary) => {
                      this.summary = fleetSummary;
                      console.log(" fleet summary:  ", this.summary);

                      for (var i = 0; i < this.summary.length; i++) {

                         var summaryData = this.summary[i];
                         console.log(" fleet summary ID:  ", summaryData.fleetId);
                         if (summaryData.fleetId == this.selectedTruckID.fleetId) {

                            this.fleetSummary = summaryData;
                            console.log(this.fleetSummary);
                            break;

                         }else {
                           this.fleetSummary = null;
                         }
                    }
                 },

                 error => this.errorMessage = <any>error);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!