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

828
Views
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 answers
Answer question

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 Report

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 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!