Не удается прочитать свойство 'длина' машинописного текста неопределенных массивов - PullRequest
0 голосов
/ 14 сентября 2018

Вот мой код:

ngOnInit(): void {
this.http.get<any>(this.getInfoArtiste)
  .subscribe(response => {
    console.log(response);
    console.log(response.artist.name);
    console.log(response.artist.image[5]['#text']);
    this.artiste.nom = response.artist.name;
    this.artiste.image = response.artist.image[5]['#text'];
    this.artiste.albums = [];
    console.log(this.artiste.albums);
  });

/* Get les albums de l'artiste */
this.http.get<any>(this.getAlbums)
  .subscribe(response => {
    console.log(response);
    for (let i = 0; i < response.topalbums.album.length; i++) {
      this.artiste.albums.push(new 

Album(response.topalbums.album[i].name, response.topalbums.album[i].image[3]['#text'], null ));
        }
        console.log(this.artiste.albums);
      });

/*    Get les chansons des albums*/
     for ( let a = 0; a < this.artiste.albums.length; a++) {
       this.http.get<any>('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=9a8a3facebbccaf363bb9fd68fa37abf&artist=' + this.artisteSelect + '&album=' + this.artiste.albums[a].name + '&format=json')
         .subscribe(response => {
           console.log(response);
         });
     }
      }

Проблема в том, что когда я добираюсь до последнего for (), он говорит, что альбомы не определены, однако я использовал его в своем пуше и с console.log, я могуувидеть его не пустой

1 Ответ

0 голосов
/ 15 сентября 2018

Вы инициализируете свой artiste.albums внутри обратного вызова подписки. Цикл for будет выполнен до завершения http-запроса.

ngOnInit(): void {
  // Initialize array outside of subscription. The array won't be initialized until the observable completes.
  this.artiste.albums = [];

  this.http.get<any>(this.getInfoArtiste)
    .subscribe(response => {
      this.artiste.nom = response.artist.name;
      this.artiste.image = response.artist.image[5]['#text'];
    });

   this.http.get<any>(this.getAlbums)
     .subscribe(response => {
        for (let i = 0; i < response.topalbums.album.length; i++) {
          this.artiste.albums.push(new Album(response.topalbums.album[i].name, response.topalbums.album[i].image[3]['#text'], null ));
        }
     });

    for ( let a = 0; a < this.artiste.albums.length; a++) {
      this.http.get<any>('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=9a8a3facebbccaf363bb9fd68fa37abf&artist=' + this.artisteSelect + '&album=' + this.artiste.albums[a].name + '&format=json')
        .subscribe(response => {
          console.log(response);
        });
    }
  }
...