Angulandy2
Angulandy2

Reputation: 806

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)

Upvotes: 0

Views: 33

Answers (3)

Skandar B.A
Skandar B.A

Reputation: 51

console.log(this.jsonObj) will run before the response of the server. You can work with it as it is. It will run perfectly. you can test it like this

<p *ngIf="jsonObj !== undefined">{{jsonObj.field}}</p>

if you want to check it with console.log, just add it in the subscription like this

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

Upvotes: 0

Sunil
Sunil

Reputation: 11243

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.
))

Upvotes: 2

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

The service method is asynchronous, so the code inside the subscribe() (which makes the assignment) executes at some time in the future, when the http call returns. Your log statement is outside of the subscription, so it happens before the assignment. Try putting the log statement inside the subscription, right after the assignment.

Upvotes: 0

Related Questions