I'm having trouble importing a JSON file into my Angular TypeScript page file that has this structure:
{
"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]
}
As a newcomer to this, I followed an online tutorial and used HttpClient to parse the file and extract data into arrays for further use in another function.
latitudes = [];
constructor(private http: HttpClient)
{
// retrieve data from the JSON file to create a JSON object
this.http.get('../../assets/data/test2.json').toPromise().then(data =>
{
for( let key in data)
{
// check if data has a key
if (data.hasOwnProperty(key))
{
// check if the key is "latitude", if true then add current data to the latitude list
if(key == "latitude")
{
this.latitudes.push(key);
this.latitudes.push(data[key]);
}
}
}
console.log(this.latitudes);
});
console.log(this.latitudes);
}
Although the data is retrieved successfully and accessible within the console.log statement inside the http get request, I encounter issues when trying to access the latitudes list from outside. It appears as undefined, even though it is displayed on the console. I intended to utilize this data for a visualization later on.
In the provided image, the top section shows the output from outside, while the section below shows the output from within. Research suggests that this could be due to a synchronization problem. Since the console output is in that order, it is possible that the outer output is processed before the inner one. Is this the root cause of the issue?