I'm trying to get the information received via JSON, but I can't access it. The data arrives, as shown in the image below: screenshot from Console
When I tried to access any property from it, I received "undefined" or "Property 'name' does not exist on type 'Track[]'".
track.service.ts:
export class TrackService {
constructor(private httpClient: HttpClient) { }
private TracksUrlPre: string = 'https://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&country=';
private TracksUrlPos: string = '&api_key=78769e93e4d6f4576ee0a1cc572f84dc&format=json';
retrieveAll(): Observable<Track[]> {
return this.httpClient.get<Track[]>(`${this.TracksUrlPre}brazil${this.TracksUrlPos}`, {responseType: 'json'});
}
}
track-list.component.ts:
export class TrackListComponent implements OnInit {
constructor(private trackService: TrackService) { }
_tracks: Track[] = [];
//_tracks2: Track[] = [];
ngOnInit(): void {
this.trackService.retrieveAll().subscribe(
track => {
this._tracks = track;
console.log(this._tracks.name); // Output: Property 'name' does not exist on type 'Track[]'
})
}
}
track.ts:
export interface Track {
tracks: {
"track": [
{
"name": string,
"duration": number,
"listeners": number,
"mbid": string,
"url": string,
"streamable": {
"#text": number,
"fulltrack": number
},
"artist": {
"name": string,
"mbid": string,
"url": string
},
"image": [
{
"#text": string,
"size": string
},
{
"#text": string,
"size": string
},
{
"#text": string,
"size": string
},
{
"#text": string,
"size": string
}
],
"@attr": {
"rank": number
}
}
],
"@attr": {
"country": string,
"page": number,
"perPage": number,
"totalPages": number,
"total": number
}
}
}
I tried this._tracks.name
, this._tracks.tracks.name
, this._tracks[0]
, this._tracks[0].name
.
I think maybe the problem is the way to access the properties inside "tracks" in the hierarchy or the data is not being allocated in the _tracks array.
CodePudding user response:
- The API returns a response with the
Track
type. In theretrieveAll
method, it should return anObservable
ofTrack
type.
track.service.ts
retrieveAll(): Observable<Track> {
return this.httpClient.get<Track>(
`${this.TracksUrlPre}brazil${this.TracksUrlPos}`,
{ responseType: 'json' }
);
}
- Declare a
_track
variable withTrack
type.
_track: Track;
- Assign the
track
value received fromretrieveAll
method to_track
. To get the first name of the item, usethis._track.tracks.track[0].name
.
this.trackService.retrieveAll().subscribe((track) => {
this._track = track;
console.log(this._track.tracks.track[0].name);
});
CodePudding user response:
this.trackService.retrieveAll().subscribe(
tracks => {
this._tracks = tracks; // array of Tracks, not Track
this._tracks.map(track => console.log(track.name)) // Track will be here
});
Don't forget to unsubscribe