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

312
Views
Can't loop through an array of objects in Typescript (Angular)

in my project I'm fetching data from an API (trip entities). This is my model:

  //Trip.model.ts
  export class Trip{
  created_at?:Date;
  updated_at?:Date;
 .... bunch of fields
}

In my component I'm fetching the data and assigning it to the trips variable. However, when I'm trying to access any of the items in the trips array I get 'undefined'. I also can't loop through it, I tried both forEach and for...in/of.
I tried using an interface instead of a class but with no luck. How can I loop through that array of objects in order to use the data in it?
Component's code:

  userName:string='';
  trips:Trip[]=[];
  moment:any=moment;
  usersData:any={};

  constructor(private auth: AuthService,
              private storage: LocalStorageService,
              private translate: TranslateService,
              private tripService: TripService){}

    ngOnInit(): void {
    console.log(this.translate.currentLang)
    this.userName=localStorage.getItem('username')!;
    this.fetchTrips();
    this.fetchPics();
  }

  fetchTrips() {
    this.tripService.getTrips().subscribe({
      next: data => {
        data[0].data.forEach((value) => {
          let trip: Trip = plainToInstance(Trip,value);
          this.trips.push(trip);
        });
      }, error: error => {
        console.log(error);
      }
    });
  }
  //fetchPics because I want to extract 
  //user's profile pics' urls from the trips array
  fetchPics(){
    console.log(this.trips);
    console.log(this.trips[0]);
    this.trips.forEach((trip)=>{
      console.log(trip);
    });
  }

getTrips service method:

getTrips(){
    return this.http.get<any>(Api.API+Endpoints.TRIP);
  }

This is what shows when I

console.log(this.trips)

after assignment.

enter image description here

Data from the API:

enter image description here

Pictures cropped to make them more readable.

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

0

You are trying to get access to this.trips value before you actually have your data on it.This happens becouse you get that data asynchronously, just inside the subscribe of this.tripService.getTrips()

So, in order to solve your problem, you just need to move this invoke:

 this.fetchPics();

inside the subscribe of fetchTrips() method, like this:

fetchTrips() {
    this.tripService.getTrips().subscribe({
      next: data => {
        data[0].data.forEach((value) => {
          let trip: Trip = plainToInstance(Trip,value);
          this.trips.push(trip);

          this.fetchPics();

        });
      }, error: error => {
        console.log(error);
      }
    });
  }
about 4 years ago · Juan Pablo Isaza Report

0

This is happening because of JS is asynchronous. you are making an http request here, that may take some time to get data from server. let's assume that might take 1 minute untill then compiler will not stop it's execution process In that 1 min of time it will execute next statements.because of that your fetchpics() method is being executed before fecthtrips() execution done. To overcome this we can use async, await as like below.

async fetchTrips() {
    this.tripService.getTrips().subscribe({
      next: data => await {
        data[0].data.forEach((value) => {
          let trip: Trip = plainToInstance(Trip,value);
          this.trips.push(trip);
        });
  }, error: error => {
    console.log(error);
  }
});

}

about 4 years ago · Juan Pablo Isaza Report

0

The function fetchPics() executes before your getTrips call ends. You need to call the method only after your HTTP call ends, and after you populate your trips array successfully.

fetchTrips() {
    this.tripService.getTrips().subscribe({
      next: data => {
        //Populate your trips array
        data[0].data.forEach((value) => {
          let trip: Trip = plainToInstance(Trip,value);
          this.trips.push(trip);
        });
        // this is where you need to call
        this.fetchPics(); 
      }, error: error => {
        console.log(error);
      }
    });
  }
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!