Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

314
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda