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

145
Vistas
Angular make an api call async and use the result

I'm trying to make an API call

ngOnInit(){
  this.function1()
}

function1(){
  this.userService.getUser()
  .then((data) => {
   this.user = data.user
   this.userM = data.userM
// here problem: If I make a console.log(this.userM) it result at the beginning empty
   if(this.userM.length > 0 ) {
       console.log("goInside")}
   else {
    console.log("doesn't enter")
     //it enters always there
   }
  }
}

in my service:

async getUser(): Promise<any>{
  let user: any = []
  let userM: any = []
  //.... operation to populate
  return {user, userM}
}

When I make an api call I would to use the this.userM array to make some operations. But it results always empty at the beginning, but it doens't enter anymore in if. How can I do?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Make use of rxjs, try using an Observable instead:

import { of } from 'rxjs';

getUsers(): Observable<any> {
  let user: any = []
  let userM: any = []
  //.... operation to populate

  return of({user, userM});
}

And then, within your component:

ngOnInit(){
  this.function1()
}

function1(){
  this.userService.getUser().subscribe((response) => {
    const { user, userM } = response;

    if (userM.length) console.log('There is data in it!')
    else console.log('No data found...');
  });
}

I suggest not using Promises in an Angular project unless necessary, you have at your disposal rxjs along with tons of useful operators for handling async calls/streams of data

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