0

I try to get data from my json file

ngOnInit() {
   this.http.get('assets/json/buildings.json',  { responseType: 'text'})
    .map(response => response)
     .subscribe(result => this.data = result);
    console.log(this.data);
}

But I get undefined... Could you please help me and explain why I do not get my data.

Anna F
  • 1,583
  • 4
  • 22
  • 42

2 Answers2

3

You're getting undefined because your calling log right away but the response that sets "data" is asynchronous, so it doesn't get set until the api returns a value.

if you did:

this.http.get('assets/json/buildings.json',  { responseType: 'text'})
  .map(response => response)
  .subscribe(result => {
     this.data = result;
     console.log(this.data);
  });

you would see the value because now you're waiting until after it has definitely been asynchronously fetched till you try to log it.

bryan60
  • 28,215
  • 4
  • 48
  • 65
0

Why are you even using the map function if you just return the response

this.http.get('assets/json/buildings.json',  { responseType: 'text'})
  .subscribe(result => {
     this.data = result;
     console.log(this.data);
  });
Melchia
  • 22,578
  • 22
  • 103
  • 117