Retrieve the data from a JSON file using Angular 4

I have a JSON data structure that looks like this:

[{"id": "ARMpalmerillas07", "type": "GreenHouse","act_OpenVentanaCen": {"type": "float", "value": 0, "metadata": {"accuracy": {"type": "Float", "value": "07/02/2018 13:08 : 43 "}}},
"act_OpenVentanaLatNS": {"type": "float", "value": 0, "metadata": {"accuracy": {"type": "Float", "value": "07/02/2018 13:08 : 43 "}}},
"act_Aerotherm": {"type": "float", "value": 0, "metadata": {"accuracy": {"type": "Float", "value": "07/02/2018 13:08 : 43 "}}},
"act_BombaCalefaccion": {"type": "float", "value": 0, "metadata": {"accuracy": {"type": "Float", "value": "07/02/2018 13:08 : 43 "}}},
"var_ValvulaPpnalCalefaccion": {"type": "float", "value": 0, "metadata": {"accuracy": {"type": "Float", "value": "07/02/2018 13:08 : 43 "}}},
"var_VoltSensorTempSuelo3": {"type": "float", "value": 3, "metadata": {"accuracy": {"type": "Float", "value": "07/02/2018 13:08 : 43 "}}}}]

Currently, I am unsure of how to work with this data. Specifically, I would like to extract the value stored in

var_ValvulaPpnalCalefaccion.value

In my code, I am utilizing the .map(res => res.json()); method in both the component and the service.

public datos: any = [];
this.datos = response;
console.log('Showing the headers:' + JSON.stringify(this.datos));

How can I correctly assign these values?

At the moment, I am attempting this:

  

public Tempext: ContextBrokerModels;

Model Definition:

export class ContextBrokerModels {
  builder(
    public type: string,
    public value: string
  ) {}
}

 

this.Tempext = response[0].var_ValvulaPpnalCalefaccion.value;

Is this approach correct?

Answer №1

You can simplify your process by following these steps. Start by creating a new class called ValvePpnalHeating:

export class ValvePpnalHeating{
    type: string;
    value: number;
    metadata = {};

    constructor(values: Object = {}) {
        Object.assign(this, values);
    }
}

Next, in your service, you can use the following code snippet:

.map((res: Response) => res.json()[0].var_ValvePpnalHeating.map(json => new ValvePpnalHeating(json)));

This will result in an

Observable<ValvePpnalHeating>

With this object, you have the flexibility to manipulate its properties, such as in the HTML {{variableValve.value}}

Note: The above code has not been tested. It is a method I have utilized in one of my projects, where you can also find additional examples...

Answer №2

//service
constructor(httpClient:HttpClient)
{}
getData()
{
      return this.httpClient.get("url").map(res=>res[0].var_ValvulaPpnalCalefaccion.value);
}
//Component
miService.getData.subscribe(res=>console.log(res));

Alternatively,

//service
constructor(httpClient:HttpClient)
{}
getData()
{
      return this.httpClient.get("url").map(res=>res[0]);
}
//Component
miService.getData.subscribe(res=>{
   console.log(res.var_ValvulaPpnalCalefaccion.value);
});

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

Desiring the ability to retrieve a JSON response from a Laravel controller for use in my javascript code

I am trying to figure out the best way to fetch data from my Laravel controller and show it using JavaScript on a webpage. How should I approach this? Here is the code snippet of my controller and ajax call: var jq = jQuery.noConflict(); var id = jq(" ...

In TypeScript Next.js 14 APP, object literals are limited to declaring existing properties

I encountered an error in my typescript next.js 14 APP. I need assistance resolving this issue, which states: Object literal may only specify known properties, and 'productPackages' does not exist in type '(Without<ProductCreateInput, Pr ...

Tips for retrieving and presenting information from a JSON document in a React TypeScript application

I am struggling to display data in a list format using TypeScript. I am able to fetch the data but unable to display it properly. I am currently using map to iterate through an array of JSON objects. //json file [ { "id": "6s", ...

Unable to link to '' because it is not recognized as a valid attribute of '' in Angular 2

I encountered an exception while working on my Angular 2 project and I'm struggling to figure out the cause. Below is the snippet of my code: ts: import {Component} from "@angular/core"; import {GridOptions} from "ag-grid"; import {RedComponentComp ...

custom form control component combined with an issue

Trying to develop a custom MatFormFieldControl with ControlValueAccessor implementation. Starting off with a familiar scenario: password form. The objective is to design a form field that takes a single string input, but contains its own internal form fo ...

Is it possible to populate the blank cells in the weekday columns for previous and following months in a mat-datepicker or mat-calendar's display?

In order to enhance user experience, I am designing a calendar that allows users to select dates. My goal is to populate the empty cells at the beginning of the first week with dates from the previous and next months. For this project, I am utilizing the ...

Error encountered when providing valid data types as arguments in a React/Typescript function

I am facing an issue when passing a string variable to a function. To address this, I have created an interface called MyMessageProps where I declare the message as a string. Subsequently, the function MyMessage utilizes this interface to return with the ...

Access the most up-to-date information through the API URL

Objective: Whenever the 'Test' Button is clicked, new data must be fetched from the backend using the API link and displayed on the modal form. Issue: If text in the input box is changed or deleted, then the modal is closed and the 'Tes ...

Property of object (TS) cannot be accessed

My question relates to a piece of TypeScript code Here is the code snippet: export function load_form_actions() { $('#step_2_form').on('ajax:before', function(data) { $('#step_2_submit_btn').hide(); $(&ap ...

What could be causing my project to install an erroneous Angular version?

It appears that my project is not utilizing the latest Angular code, but I am unsure of the reason behind this. I have checked my package.json file and found the following dependencies: "devDependencies": { "@angular/common": "2.0.0", "@angular ...

Identify the locality and apply it to the root module of Angular 2 by utilizing a provider

I am working on a function that detects the current locale and I need to set it in the root App module of Angular 2 using a provider so that I can access it in all other components. I understand that I can achieve this by following the code below: { pr ...

Saving a JSON object to multiple JSON objects in TypeScript - The ultimate guide

Currently, I am receiving a JSON object named formDoc containing data from the backend. { "components": [ { "label": "Textfield1", "type": "textfield", "key": "textfield1", ...

Python code to transform a CSV file into JSON format is not working properly due to

I have created a python script to convert a CSV file into a JSON file. However, the output does not match my expectations. I would appreciate it if you could take a look and suggest any necessary modifications. Here is the format of the desired JSON file: ...

How can I make my webpage fill the entire width of an iPhone screen when in landscape mode using Angular or React?

While testing my website on my iPhone, I noticed a significant gap appearing on either side of the app in landscape view in Safari. Is there a solution to fix this issue? The problem occurs in both Angular and React applications, examples of which are disp ...

When using JsonConvert.DeserializeObject from Newtonsoft.Json, the issue of losing a non-printable ASCII character (specifically the group separator) during deserialization may

I have encountered a puzzling issue that I am struggling to resolve. My current task involves deserializing JSON data using Newtonsoft.Json. After inspecting the raw JSON string, I noticed certain character sequences: { '\\', 'u&ap ...

On the subsequent iteration of the function, transfer a variable from the end of the function to the beginning within the same

Can a variable that is set at the end of a function be sent back to the same function in order to be used at the beginning of the next run? Function function1 { If(val1.id == 5){ Console.log(val1.id val1.name) } else{} Val1.id = 5 Val1.name = 'nam ...

"Unlocking the potential of RavenDB 4.0 with raw json data storage

Currently, I am utilizing NLOG for logging purposes with the JsonLayout and my goal is to save these logs in RavenDB 4.0. Essentially, I am attempting to store raw JSON data into RavenDB using the RavenDB .NET client. In the past, I had a functioning solu ...

Exploring the Response Object in Express JS: A Comprehensive Guide

I'm currently using Express version 4.13.4. My goal is to access and examine the res object. However, when I try to use console.log() on it, the output is too lengthy to display properly in a command window. I attempted to utilize jsonfile to save i ...

How can you implement Jquery Ajax function for enhancing the Ecommerce Category Layout?

For a client, I am developing a custom ecommerce website where I intend to use Ajax to update the product layout dynamically based on user selections. This means that when a visitor picks a color like red, blue, or green from a list, the Ajax script will p ...

Updating the JSON object wrapper name received from a WCF service method

In my WCF 3.5 application, I have created a method called TestMe with the following definition: [OperationContract] [WebInvoke(UriTemplate = "/Login", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseForma ...