我似乎在将返回的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;
}
我的Service类和方法是:
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'返回空白?我看过一些教程,对于大多数教程来说,数组是填充的,但不是我的。不确定我缺少什么?
答案 0 :(得分:0)
假设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)
);
}
答案 1 :(得分:0)
console.log
实际上是首先执行,因为可观察对象具有异步性和.subscribe
功能this.spotifyAudioFeaturesArray = data;
在POST请求之后执行 (第二个console.log
spotifyAudioFeaturesArray : SpotifyAudioFeatures[];
,因此它尚未包含任何值。因此打印undefined
答案 2 :(得分:0)
您正在记录spotifyAudioFeaturesArray
的内容,然后实际填充,因为getAudioFeatures
是异步请求。您的代码工作正常,您的console.log
语句在错误的位置。
将您的console.log
语句移到您的subscribe
块中,它应该正确记录内容。
getAudioFeatures(track) {
this.spotifyService.getAudioFeatures(track).subscribe(
(data) => {
console.log(data);
this.spotifyAudioFeaturesArray = data;
console.log(this.spotifyAudioFeatures);
},
(err) => console.log(err)
);
}