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

The error TS2304 occurs when the e2e tsconfig types cannot find the name 'browser'

I am facing challenges while setting up a sample angular project with a basic webdriverio end-to-end test, encountering some compilation errors in my e2e test. Setting up tsconfig The project is configured with the following key files: e2e / test / [e2e t ...

Is there a way for me to extract information from the FAQs on this website?

Here is the URL I need to access for this project. This webpage presents questions in collapsed form, and clicking on them reveals corresponding answers. My objective is to convert these questions into keys and their respective answers into values. For i ...

What are some ways to optimize the performance of a Select Box?

I am attempting to show a lengthy list of countries in an ion-select. Currently, there are 249 countries that I need to load. Unfortunately, the rendering performance is quite slow on my phone. <ion-list margin-top margin-bottom> <ion-item> ...

In the context of Angular, the ELSE statement continues to run even after the IF condition has been satisfied within

Currently, I am utilizing Angular 11 in conjunction with Firestore. Within my code, I am fetching data using the subscribe method from an API service. Subsequently, I am employing a for loop to extract object values in order to verify if a value within a c ...

Insert dynamic values into div attributes

I am looking for a way to dynamically add div attributes in Angular 7. Here is what I attempted: <div *ngFor="let e of etats._embedded.etats" style="background: {{e.codeCouleur}} !important;" data-code="{{e.id}}" data-bg={{e.codeCouleur}}>{{e.no ...

When using json.dumps, it appends the attribute '"__pydantic_initialised__": true' to the object

I have been experimenting with fastapi and working with data from json files. One issue I encountered is that when I use app.put to add an object, json.dumps automatically adds the attribute "__pydantic_initialised__": true to the newly created o ...

Accessing data from the subscribe method

When attempting to use certain values for graphs, I encountered an issue where the value returned becomes undefined once outside of the subscribe function. I have experimented with putting the values in an array of objects but still believe this is the co ...

Exploring Angular: Enhancing Routing through GET Requests

I've been working on a cutting-edge application that combines an Angular 2 frontend with a powerful Java backend. An exciting feature of this application is a dynamic form, consisting of various search criteria. Upon submission, I execute an http get ...

What is causing the element to disappear in this basic Angular Material Sidenav component when using css border-radius? Check out the demo to see the issue in action

I have a question regarding the Angular Material Sidenav component. I noticed that in the code below, when I increase the border-radius property to a certain value, the element seems to disappear. <mat-drawer-container class="example-container" ...

Error message: The protocol "https:" is not compatible with this function. Please use "http:" instead

I decided to use IBM Bluemix for my school project, where I am working on creating a web service. For my project, I need to fetch JSON data from an API in order to utilize the provided information. Currently, I am utilizing the http get method to retrieve ...

What is the method for integrating JSON into the gdata objective-c framework?

After following the instructions provided in this guide to integrate the framework: However, during the compilation process, I encountered the following error: Error: /devfolder/gdata-objectivec-client-read-only/Source/JSON/SBJsonBase.h: No such file or ...

Creating Production Files for Web using RxJs and TypeScript

I am interested in developing a JavaScript Library using RxJs (5.0.0-Beta.6) and TypeScript (1.8.10). My TypeScript file is successfully compiling. Below are the files I have: MyLib.ts: /// <reference path="../../typings/globals/es6-shim/index.d.ts" ...

Is it possible to convert a DynamoDB AttributeMap type into an interface?

Assume I define a TypeScript interface like this: interface IPerson { id: string, name: string } If I perform a table scan on the 'persons' table in DynamoDB, my goal is to achieve the following: const client = new AWS.DynamoDB.Documen ...

What's the deal with TypeScript tsconfig allowing .json imports, but not allowing them in built .js files?

By including the line "resolveJsonModule": true in my project's .tsconfig file, I have successfully implemented direct importing of data from .json files. The project functions properly, even when using nodemon. However, upon building the project and ...

Update the style dynamically in Angular using an ngFor directive and an array of data

Is there a way to dynamically set the width using data from an array in Angular? The usual approach doesn't seem to work. How can I solve this issue? <div *ngFor="let item of products"> <div [style.width.px]="item.size" class="Holiday"&g ...

Getting started with Angular 7 and ng-bootstrap: the ultimate setup guide

I recently began incorporating ng-bootstrap into my project. After doing some research online, I discovered that in order to use ng-bootstrap, I needed to install both Bootstrap 4 and ng-bootstrap. I created a new project and installed the following: "@ng ...

Personalized AbstractCursor with JSON data

Can the cursor class be used to expose a json object? I created a custom abstract cursor with a parameter as a json object, but I am having trouble overriding the abstract cursor's moveToFirst/moveToNext methods to support iteration. Any suggestions o ...

Having trouble displaying a JSON response on an HTML page with AJAX

I've written an AJAX function that goes like this: function ajx(){ var ajaxRequest; // This variable makes Ajax possible! try{ // Works in Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // For Internet Exp ...

Create an interactive slider using only images in an Ionic Angular content display

I need help transforming the images from WordPress into a slider instead of showing them individually. How can I achieve this? <ion-content padding> <div *ngIf="selectedItem" class="selection"> <h2 [innerHTML]="selectedItem.title.rend ...

The server cannot process the content type 'application/json;charset=UTF-8' as it is not supported

As a newcomer to the Spring World, I am venturing into my first Jquery journey. I am attempting to retrieve JSON data from a JSP page using an Ajax call to the controller. Unfortunately, I encountered an error: org.springframework.web.HttpMediaTypeNotSuppo ...