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

838
Vistas
Angular - subscribe data to observable returns undefined

I'm working on an Angular project. but I have problem when I subscribe the data to observable is returning undefined

and I have a service method that returns data from HTTP.

public serviceMethod(): Observable<WordList[]> {
const url = `${this.baseUrl}/wordLists`;

   return this.httpClient.get<GetResponseWordList>(url).pipe(
      map(response => response._embedded.wordLists)

   );
}

and a component method that takes the data from the service and assigns it to an "array"

  componentMethod() {

  // get from the service
  this.otherService.serviceMethod().subscribe(
    data => {
      this.array = data;


    }
  );

}

I have another method in the same file that use the "array"

secondMethod(){
    console.log(this.array)
}

Finally, I have the main method that uses both the last two methods.

 mainMethodMethod(){
    componentMethod();
    secondMethod();
}

the componentMethod() is run first. However, always get an "undefined" value of the array

one solution is to put the secondMethod() inside componentMethod() when to subscribe the data. But I don't want to do that because I need to use a loop and that will take too long.

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

0

You have to call your secondMethod in the subscribe function after the data variable.

It gets undefined since its asynchronous, it has to wait for the data to finish loading then call your next functions.

If you call it after the first method then the 2nd method will get executed without the first

about 4 years ago · Juan Pablo Isaza Denunciar

0

I think that you should clarify this part of your question :

"But I don't want to do that because I need to use a loop and that will take too long"

What is the loop you need to use ? Because it's constraint that is maybe the base of the problem ...

With what you explained, I see (at least) this solution :

componentMethod() {
  // get from the service
  return this.otherService.serviceMethod().pipe(
    map(data => {
      this.array = data;
    })
  );
}

mainMethodMethod(){
    componentMethod().subscribe(() => {
        secondMethod();
    })
}
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