What is the best way to store JSON data as an object in memory?

How do I convert the result of an HTTP request from JSON format to an object in TypeScript?

Below is the code snippet:

Component:

import { Component } from '@angular/core';
import { DateTimeService } from './datetime.service';
import { DateTime } from './datetime'

@Component({
  selector: 'my-app',
  moduleId: module.id,
  templateUrl: 'app.component.html',
  providers: [DateTimeService]
})

export class AppComponent {

  constructor(private _dateTimeService: DateTimeService){ }

  dateTime: DateTime = new DateTime();

  getDateTime() {
    this._dateTimeService.getDateTime().subscribe(data => this.dateTime = data,
      error => alert("error"),
      () => alert("done"));
    debugger;

    alert(this.dateTime.date);
    alert(this.dateTime.milliseconds_since_epoch);
    alert(this.dateTime.time);

  }
}

Service:

import { Http } from '@angular/http';
import {Injectable} from'@angular/core';
import 'rxjs/add/operator/map'
import { DateTime } from './datetime'

@Injectable()
export class DateTimeService{
    constructor(private _http: Http) { }
    getDateTime()  {
        return this._http.get('http://date.jsontest.com').map(res => <DateTime>res.json());
    }
}

Upon running the code, all properties of the DateTime object are undefined. However, if I do not cast the incoming data to be of type DateTime in my service and use JSON.stringify(data.time) instead, I am only able to access a single property.

Answer №1

Your alerts are currently undefined because they are being triggered before the data has been retrieved.

getDateTime() {
    this._dateTimeService.getDateTime().subscribe(data => this.dateTime = data,
      error => alert("error"),
      () => alert("done"));
    debugger;
    alert(this.dateTime.date);
    alert(this.dateTime.milliseconds_since_epoch);
    alert(this.dateTime.time);
}

To ensure your alerts work correctly, place them inside the subscription as shown below:

getDateTime() {
    this._dateTimeService.getDateTime().subscribe(data => { 
    this.dateTime =  data;
    alert(this.dateTime.date);
    alert(this.dateTime.milliseconds_since_epoch);
    alert(this.dateTime.time);
  });
}

Since this is an asynchronous call, the code is not executed in the order it's written. If you're having trouble displaying your data in the view, consider using the safe navigation operator or *ngIf.

Dealing with asynchronous operations is common, so you may need to use techniques like the ones mentioned above to handle data retrieval and rendering correctly.

One approach is to use *ngIf in your template like this:

<div *ngIf="dateTime">
  <!-- Your code here -->
</div>

This will only display the content inside the div once the dateTime values are available.

Alternatively, you can use the safe navigation operator like this:

{{dateTime?.date}}
{{dateTime?.milliseconds_since_epoch}}
{{dateTime?.time}}

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

What could be the reason for encountering an "Uncaught Runtime Error" specifically on an Android emulator while using a React app?

I'm encountering an issue when trying to launch a web-based React app on Chrome within an Android emulator. The error message I'm receiving is as follows: "Unhandled Runtime Error Uncaught SyntaxError: Unexpected Token ." Interestingly, the same ...

Employing an unchanging Map format for observation

I'm currently working on implementing a synchronization mechanism using observable and Map structures from Immutable.js. However, I'm encountering an issue where the Map is unable to function as an observable or perhaps I might be approaching it ...

Utilizing PostgreSQL for an array of objects

My goal is to develop a function that can accept a JSON input, which consists of an array of objects. However, I encounter an error when trying to store this array in a variable using postgresql. create function test_create_table(_data json) returns void ...

Enhance the Nuxt 3 experience by expanding the functionality of the NuxtApp type with

When I include a plugin in my NuxtApp, it correctly identifies its type. https://i.stack.imgur.com/UFqZW.png However, when I attempt to use the plugin on a page, it only displays the type as "any." https://i.stack.imgur.com/hVSzA.png Is there a way for ...

How can I determine if an Angular library is compatible with the specific version of Angular that my application is utilizing?

My Angular 8 application is currently running on a version that's quite outdated compared to the latest release of Angular. When it comes to incorporating Angular libraries, how can I determine if they are compatible with Angular 8? Is there a strict ...

POST requests in Express node sometimes have an empty req.body

Server Code: const express = require('express') const app = express() app.use(express.static('public')) app.use(express.json({limit :'100mb'})); app.post('/post', (req, res) => { console.log('post called ...

Saved as a list in serialized form, with only a single record stored

I managed to retrieve a list containing an example of 1 ID: 12 History and stored it in the Customer model for mapping, placing it under customerList to consolidate it. However, when I attempted to serialize it, the output appeared as follows. If the cust ...

Python is able to transform a string into a dictionary

I'm attempting to transform a specific string into a dictionary by utilizing the JSON library. string = {u'ItemID': u'474178239', u'Status': 1, u'ImageURL': u'https://img.shopstyle-cdn.com/pim/d2/1a/d21a54 ...

Attempting to retrieve data from a JSON file according to the choice made by the user in a dropdown menu

My goal is to create a user interface where users can select options from a drop-down list and receive corresponding output based on their selection. The drop-down list options are populated using data from a JSON file, and the desired output is derived fr ...

Limiting only one checkbox to be selected in a dynamic FormArray in Angular requires some custom logic. This can

I am working on designing an Angular-12 dynamic FormArray: import { Component, OnInit, VERSION } from '@angular/core'; import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selecto ...

Utilizing String.Format in TypeScript similar to C# syntax

Is there a way to achieve similar functionality to String.Format in C# using TypeScript? I'm thinking of creating a string like this: url = "path/{0}/{1}/data.xml" where I can substitute {0} and {1} based on the logic. While I can manually replace ...

Exclusive Vue3 Props that cannot be used together

How can a component be created that accepts either json with jsonParserRules or jsonUrl with jsonParserRulesUrl, but not both? It would be ideal if the IDE could provide a warning when both props are specified. Example of an Attempt that does not Work < ...

"Import data from a text file and store it as an array of objects using Types

I need assistance with converting the information in my text file into an array of objects. Below is a snippet of the data from the text file: DOCNO NETAMOUNT IREF1 IREF2 DOCDT 001 30000 50 100 6/7/2020 2 40000 40 90 6/7/2020 Currently, t ...

How can you position the input cursor at the end of the default text when navigating through fields with the tab key?

I've implemented tab index in the HTML to navigate from one field to another. In the image below, you can see me tabbing from "Revise" to "Link". https://i.stack.imgur.com/vb6L.png However, when I press tab, the default text in the Link field is fu ...

Navigating to view component in Angular2 Routing: Issue with router-link click event not working

I have set up my app.routes.ts file and imported all the necessary dependencies. Afterward, I connected all the routes to their respective Components as follows: import {ModuleWithProviders} from '@angular/core'; import {Routes, RouterModule} f ...

Having trouble retrieving JSON data from the server in an Android application

I have been working on an Android project where I need to fetch a JSON file from a specified URL. This JSON file contains the URLs for both the video and the image thumbnail that are supposed to be displayed in the app. However, I'm encountering an i ...

The map buttons are located underneath the map, and unfortunately, it seems that setting the map height to 100% using Angular is

Upon completing the creation and display of the map, an unusual occurrence is taking place where the map buttons ("Zoom rectangular, map settings, and scale bar") are appearing below the map as oversized icons. Additionally, there is a challenge when setti ...

Converting SQL database constraints to JSON format using PHP

If we consider the database structure for car manufacturers and their corresponding cars, it looks like this: manufacturers: ---------------------------------- | manufacturer | founded_in | id | |--------------|------------|----| | Toyota | 1937 ...

Getting a JSON file from a Minio server using node.js

Currently, I am trying to retrieve a json file from minio and then insert it into mongoDB using mongoose. When I use the getObject method, I am receiving a Buffer object Below is the code snippet that showcases my approach: let miniData minioClient.get ...

Sending every piece of information to the URL may not be the most efficient approach, in my opinion

Lately, I have incorporated NodeJS into my Angular project and here is how I am currently implementing it: Node : app.get('/register/:username/:password', function(req, res){ db.collection('users').insertOne({ username: req ...