首页 > 解决方案 > Angular将JSON转换为模型并存储在数组中

问题描述

我似乎在将返回的 JSON 映射到我的对象数组时遇到了问题。这是我想要转换为对象并放入数组中的 JSON。

{ danceability: 0.653,
  energy: 0.59,
  key: 5,
  loudness: -9.649,
  mode: 1,
  speechiness: 0.104,
  acousticness: 0.000942,
  instrumentalness: 0.378,
  liveness: 0.2,
  valence: 0.625,
  tempo: 168.054,
  type: 'audio_features',
  id: '7bsPIUEEOuL5WlOPcYUrYx',
  uri: 'spotify:track:7bsPIUEEOuL5WlOPcYUrYx',
  track_href: 'https://api.spotify.com/v1/tracks/7bsPIUEEOuL5WlOPcYUrYx',
  analysis_url: 'https://api.spotify.com/v1/audio-analysis/7bsPIUEEOuL5WlOPcYUrYx',
  duration_ms: 293307,
  time_signature: 4 }

这是我的对象界面。它被称为 SpotifyAudioFeatures

export interface SpotifyAudioFeatures {
  danceability: number;
  energy: number;
  key: number;
  loudness: number;
  mode: number;
  speechiness: number;
  acousticness: number;
  instrumentalness: number;
  liveness: number;
  valence: number;
  tempo: number;
  type: string;
  id: string;
  uri: string;
  track_href: string;
  analysis_url: string;
  duration_ms: number;
  time_signature: number;
  }

我的服务类和方法是:

getAudioFeatures(tracks): Observable<SpotifyAudioFeatures[]>{
    return this.httpClient.post<SpotifyAudioFeatures[]>('http://localhost:3000/getAudioFeatures', 
    {
      'tracks' :tracks
    }
    ).pipe(catchError(this.handleError));
  }

我在 component.ts 上的方法是:

  spotifyAudioFeaturesArray : SpotifyAudioFeatures[];


    getAudioFeatures(track){
        this.spotifyService.getAudioFeatures(track).subscribe(
          (data) => {
            console.log(data);  //I can see the JSON printed here
            this.spotifyAudioFeaturesArray = data;           
          },
          (err) => console.log(err)
        );
          console.log(this.spotifyAudioFeatures)  //This shows up as undefined   
      }

我不确定为什么数组 'spotifyAudioFeaturesArray' 返回空白?我看过一些教程,其中大多数都填充了数组,但不是我的。不确定我错过了什么?

标签: angular

解决方案


假设这console.log(this.spotifyAudioFeatures)是您检查它的唯一地方,这可能是spotifyService.getAudioFeatures()函数异步性质的结果。

由于 Observables 的异步特性,JS 调用this.spotifyService.getAudioFeatures()但不等待结果,而是转到console.log(this.spotifyAudioFeatures).

由于getAudioFeatures()尚未完成执行,this.spotifyAudioFeatures因此仍未定义。

要修复它,请尝试将 console.log 放在后面this.spotifyAudioFeaturesArray = data;

像这样:

getAudioFeatures(track){
    this.spotifyService.getAudioFeatures(track).subscribe(
      (data) => {
        console.log(data);
        this.spotifyAudioFeaturesArray = data;
        console.log(this.spotifyAudioFeatures);       // here   
      },
      (err) => console.log(err)
    );
}

推荐阅读