Search code examples
jsonangularhttpangular-httpclient

Angular 2 get json data and define it as new array in component


I got my json file and I am getting it on the service. Then I am trying to subscribe to it in the component, but in console.log(this.jsonObj) I get empty array. Also if I write console.log(data) - I get json data.

Service :

objUrl = 'assets/jsons/obs.json';
constructor(private http: HttpClient) {
  console.log('Hello ObjectsProvider Provider');
}
getObjectsJson() {
  return this.http.get(this.objUrl);
}

Component :

jsonObj = {};
this.object.getObjectsJson().subscribe((data =>
  this.jsonObj = data
))
console.log(this.jsonObj)

Solution

  • Issue

    You are trying to get the Asynchronous data in Synchronous fashion. You are logging the data console.log(this.jsonObj) outside of Observable. So it will get executed without waiting for the result to come from API.

    Fix

    Just move the log or any code you want to execute the after API inside subscribe. So you your code will look like

    jsonObj = [];
    this.object.getObjectsJson().subscribe((data =>
      this.jsonObj = data;
      console.log(this.jsonObj);  //<-- data will be appear here.
    ))