Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

198
Views
problem with access object property in typescript angular

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 Spotify web API to my playlist object like this

for (let i = 1; i <= iterationCount; i++) {
    const endpointX = `${BASE_API_URL}playlists/${playlistId}/tracks?limit=${PLAYLIST_ITEM_LIMIT}&offset=${i}&fields=${fieldString}`;
    const subscription: Subscription = this.http.get<WritableTrackList>(endpointX).subscribe(data => {
      for (const item of data.items) {
        const track: Track = this.helperService.trackApiObject2TrackObject(item.track);
        this.playlist.tracks.push(track);
      }
    });    
}

When I try to print playlist object in the javascript console with console.log(this.playlist);, it's working. 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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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[]
}
about 4 years ago · Juan Pablo Isaza Report

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!