Home > front end >  problem with access object property in typescript angular
problem with access object property in typescript angular

Time:10-17

I have a typescript object like this

const playlist: { tracks: Array<Track> } = { tracks: new Array<Track>() };

And this is Track interface

interface Track {
  title?: string;
  album?: string;
  artists?: string;
  duration?: string;
  explicit?: boolean;
  url?: string;
}

I'm trying to get data from enter image description here

Buth I try to print playlist.tracks with console.log(this.playlist.tracks);, it's print an empty array

enter image description here

Why can't I access the tracks property of the playlist object? How can i access this property? Any solution?

CodePudding user response:

try this :

console.log(this.playlist['tracks']);

if you want to use like this.playlist.tracks you must declare an interface for playlist:

interface PlayList{
tracks:Track[]
}

CodePudding user response:

maybe try to print it inside the subscription.

    .subscribe(data => {
          for (const item of data.items) {
            const track: Track = this.helperService.trackApiObject2TrackObject(item.track);
            this.playlist.tracks.push(track);
          }

console.log([...this.playlist.tracks])

        }); 

// printing outside subscription will most likely give an empty array

although in general you would want something reactive

tracks$ = this.http.get<WritableTrackList>(endpointX).pipe(map(trackApiObject2TrackObject));

then in the template

<ng-template ngFor let-track[ngForOf]="tracks$| async">
<app-track [track]></app-track>
</ng-template>
  • Related