William Lake.
William Lake.

Reputation: 81

Angular 2 _this is undefined

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

Upvotes: 2

Views: 1330

Answers (1)

Aravind
Aravind

Reputation: 41571

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 = [];

Upvotes: 3

Related Questions