Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

322
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda