1

I am writing a code in Angular where the JSON response (array of JSON) from a REST call needs to be displayed as a table on GUI. The JSON format is not pre-defined and I need to capture in in some generic format and then use it. The piece of code is as follows:

getResultsFromDB() {
  this.http.get('app/api/locSearchReq.json').subscribe(
    data => {
      **this.locResults = data as any;**
    },
    (err: HttpErrorResponse) => {
      console.log (err.message);
    }
  );
  console.log('Data ' + this.locResults);
}

If I move console.log call within subscribe, it prints the retrieved data. But I am not able to access this.locResults outside the subscribe call or outside the function.

Other similar functions which I have written, where I am receiving pre-defined Json array as response and is mapped to a typescript class, I am able to access the data outside the function.

  getResultItems() {
    this.http.get(this.glResultItems).subscribe(
      data => {
        this.resultItems = data as ResultItem [];    
      },
      (err: HttpErrorResponse) => {
        console.log (err.message);
      }
    );
  }

When I try to access this.resultItems outside the function, I am able to do so. I am not able to understand what am I doing wrong or different here,

Data in locSearch.json is as follows:

[{
    "name": "sookshm",
    "age": "27",
    "org": "abc",
    "location": "NJ",
    "expertise": "javascript"
}, {
    "name": "Liu",
    "age": "35",
    "org": "ibm",
    "location": "NJ",
    "expertise": "css"
}, {
    "name": "Mike",
    "age": "38",
    "org": "msn",
    "location": "NY",
    "expertise": "html"
}]

In browser console it shows this.locResults as undefined.

Need help with paring/handling this response.

Sookshm
  • 11
  • 2
  • Try to put console in ```data => { this.locResults = data as any; console.log(this.locResults);}``` . In your code console loges the array befor the response arrives . – Fateme Fazli Apr 20 '18 at 20:37
  • As @fatemefazli said, you have put console.log at wrong place. Put it inside your subscribe body. – Agam Apr 20 '18 at 20:52
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Estus Flask Apr 20 '18 at 21:37
  • Of course it's undefined. The http get line returns immediately and the console log line runs immediately afterwards. Once the data has been received, the assignment line happens (after the aforementioned lines have run) – ProgrammingLlama Apr 21 '18 at 04:00
  • Is this still an issue or did you solve the problem? –  Apr 21 '18 at 08:36
  • Thanks. Now I understood how it is working. – Sookshm Apr 23 '18 at 11:58

0 Answers0