2

I'm getting an error in the function call below saying that this.albumDetails is undefined for a specific line even though all other this calls are working fine.

the error is: TypeError: _this.albumDetails is undefined

The error probably occurs at this.albumDetails.concat(items) where items is an array of json objects

Any assistance is appreciated thanks.

export class AppComponent {
albums: any[];
albumDetails: any[];
searchAlbum(input: any){
    this.show = true;
    this.searchService.getAlbum(input).subscribe(data => {
      this.albums = data;
      for(var i = 0; i < 50; i++){
        this.searchService.getDetails(this.albums[i].artist, this.albums[i].name, this.albums[i].mbid).subscribe(items => {
          this.albumDetails = this.albumDetails.concat(items); //Error occuring here at this.albumDetails.concat(items)
          console.log(this.albumDetails);
        });
      }
    });
  }
 }

1 Answers1

3

Initialize the albumDetails to empty string

albumDetails : string =' '

Alternatively you can use ES5 syntax for string concatenation as

this.albumDetails = `${this.albumDetails}${items}`;

Using backtick

` `

Reference Stackoverflow Post

Update 1 : As per comment

It seems that albumDetails is an array, so an array has to be initialized before pushing elements, so add the below line out of the for loop

this.albumDetails = [];

or during the variable declaration

albumDetails = [];
Aravind
  • 40,391
  • 16
  • 91
  • 110
  • Damn maybe i'm using the wrong function here, i'm trying to push an array from a json call to albumDetails so that i have an array of arrays. I should probably use .push here instead of .concat, but I still get the undefined error nonetheless – William Lake. Sep 16 '17 at 08:22
  • `albumDetails` is an array or a string?? can you add the complete post – Aravind Sep 16 '17 at 08:24
  • sorry I assumed that it would be clear that an array was already initialized, i have updated the code in the question. – William Lake. Sep 16 '17 at 08:30
  • @WilliamLake. updated answer should work. is it working or need more help? – Aravind Sep 16 '17 at 08:39