I am trying to import a JSON file into my Angular typescript page file that looks like:
{
"latitude": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
"longitude": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
"value":[53, 95, 3, 10, 239, 102, 604, 58, 82, 105, 220, 68]
}
I'm new to this, so from a tutorial online I used HttpClient to go through the file and move data into arrays for usage in another function.
latitudes = [];
constructor(private http: HttpClient)
{
// grab the data from the json file and creates a JSON object
this.http.get('../../assets/data/test2.json').toPromise().then(data =>
{
for( let key in data)
{
// checks if data has a key
if (data.hasOwnProperty(key))
{
// check if key = latitude, if true then push current data to latitude list
if(key == "latitude")
{
this.latitudes.push(key);
this.latitudes.push(data[key]);
}
}
}
console.log(this.latitudes);
});
console.log(this.latitudes);
}
And while it does get the data, when trying to access the latitudes list, the console.log inside the http get request is able to use the data freely. However, when outside I am unable to access the data despite it still sort of showing up on console.log, and when trying to access the data from the outside, it is saying it is undefined. I was hoping to be able to use this data for making a visualization later.
In the picture, the top is output from the outside, and the one below is from inside. Reading around I heard it's because of a synchronization issue or something? Since the console output is in that order, is it because the outer output is running before the inner one?