Attempting to interpret and apply information extracted from a JSON document

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.

view console output

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?

Answer №1

Here is a straightforward method to accomplish this task:

this.http.fetch('../../data/sample.json').toPromise().then(response =>
    {
      Object.keys(response)?.forEach(property =>
      {
        if(property === "latitude")
        {
          this.latitudeValues = response[property];
        }
      });

      console.log(this.latitudeValues);
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to modify the information retrieved from JSON?

I've integrated the OMDB api (Online Movie DB) into my project. The interface I created is returning the expected data types, with data being returned as {Search: Array(10), totalResults: "31", Response: "True"} when using the http get method. The spe ...

When using TypeScript, it is important to ensure that the type of the Get and Set accessors for properties returning a

Why is it necessary for TypeScript to require Get/Set accessors to have the same type? For example, if we want a property that returns a promise. module App { export interface MyInterface { foo: ng.IPromise<IStuff>; } export int ...

Navigating through concealed pathways

I have defined the following simple route configuration: const appRoutes: Routes = [ { path: 'login', component: LoginComponent }, { path: '', component: WidgetComponent }, { path: 'P3', comp ...

Troubleshooting Problem with Angular 2 Filters

Here is an example of how I am utilizing the filter: <ion-item *ngFor="let contact of contacts | isMember"> <ion-label>{{contact.name}}</ion-label> {{contact.phoneNumber}}-{{contact.isMember}} </ion-ite ...

Tips on how to restore the default value for a select dropdown in Angular 2

Is there a way to reset a select element back to its first option when the clear button is clicked? I have a select with the first option serving as a placeholder, but I'm having trouble resetting it. <select class="form-control" aria-placeholder= ...

Issue: Typescript/React module does not have any exported components

I'm currently facing an issue with exporting prop types from one view component to another container component and using them as state type definitions: // ./Component.tsx export type Props { someProp: string; } export const Component = (props: ...

Having trouble importing the datamap library into the HTML of an Angular 2 application

I am currently in the process of developing a small Angular 2 application for educational purposes, and my intention is to incorporate datamaps for the map interface. However, there is no directive available for this library yet, so I am experimenting wit ...

Testing Angular: How to Unit-test HttpErrorResponse with custom headers using HttpClientTestingModule

In the code snippet below, I am attempting to find a custom header on error: login(credentials: Credentials): Observable<any> { return this.http.post(loginUrl, credentials) .pipe( catchError((httpErrorResponse: HttpErrorRespo ...

Jest is unable to handle ESM local imports during resolution

I am encountering an issue with my Typescript project that contains two files, a.ts and b.ts. In a.ts, I have imported b.ts using the following syntax: import * from "./b.js" While this setup works smoothly with Typescript, Jest (using ts-jest) ...

Angular form with dynamically generated nested inputs

I am attempting to extract the values from the input fields within this dynamically generated form. Each time the user clicks the button, new input fields are added. However, I am unsure of the correct method to retrieve this data based on the documentatio ...

Adding properties with strings as identifiers to classes in TypeScript: A step-by-step guide

I am working with a list of string values that represent the identifiers of fields I need to add to a class. For instance: Consider the following string array: let stringArr = ['player1score', 'player2score', 'player3score' ...

I am encountering an error in TypeScript stating that a property does not exist on the Response type

Hey there, I've been working on a custom advanced results page that allows for various queries like /articles?name="". This is my first time using TypeScript and while migrating my code over, I encountered a TypeScript error at the very end. // esli ...

Difficulty transferring information between two components by using services

I am trying to pass the values of an array from the Search component to the History component in order to display the search history. My current code structure looks like this: search-page.component.ts export class SearchPageComponent implements OnInit ...

How can I structure the response from HttpClient to make it compatible with *ngFor

I need assistance in solving a minor issue. I am working with data from a REST API, which is returned as an array of objects. After receiving this data in my service, I attempt to transform it and push it to a subject to notify my component about the arriv ...

Issue with Component in Angular not functioning properly with proxy construct trap

Currently working with Angular 17, I have a straightforward decorator that wraps the target with Proxy and a basic Angular component: function proxyDecorator(target: any) { return new Proxy(target, { construct(target: any, argArray: any[], newTarget: ...

Reference element of a row within a material table

Is there a method to obtain the element reference of a specific row in mat-table? The data is being fetched from an API, and I intend to show a popover above a row in mat-table. Popover necessitates an element reference or HTML element to be connected to ...

NativeScript does not acknowledge the permission "android.Manifest.permission.READ_CONTACTS"

Hi there! I am a beginner in mobile development and currently learning Angular 2. I am facing an issue with requesting permission for reading contacts in NativeScript. It seems that "android" is not being recognized. For instance, when trying to execute t ...

What is the best way to implement a counter with setInterval in Angular?

As a beginner in Angular, I am trying to utilize the setInterval function to count numbers, but I am facing difficulties in achieving success. Can someone provide assistance with this issue? (Apologies for any grammar mistakes in my English.) Thank you in ...

Implementing a more efficient method for incorporating UUIDs into loggers

------------system1.ts user.on('dataReceived',function(data){ uniqueId=generateUniqueId(); system2.processData(uniqueId,data); }); ------System2.ts function processData(u ...

The guide to integrating the npm package 'mysql-import' into a node.js project with TypeScript

I'm currently facing an issue while trying to import a dump to a database using node.js and the npm module 'mysql-import'. Initially, I wrote the code in JavaScript and it worked flawlessly. However, when I attempted to modify it for TypeScr ...