Utilizing a powerful combination of Angular 5, PrimeNG charts, Spring Boot, and JHipster

I am facing an issue with creating charts using PrimeNG. The main challenge I'm encountering is the conversion of data from a REST API in Angular 5 (TypeScript) and retrieving the list of measurements from the API. I have an endpoint that returns my measurements as JSON. To demonstrate, I have included a sample line chart in my application:

import { Component, OnInit } from '@angular/core';
import { JhiLanguageService } from 'ng-jhipster';
import { Message } from 'primeng/components/common/api';

@Component({
    selector: 'jhi-linechart',
    templateUrl: './linechart.component.html',
    styles: []
})
export class LinechartComponent implements OnInit {
    data: any;
    msgs: Message[];

    constructor() {
        this.data = {
            labels: ['February', 'March', 'April', 'May', 'June', 'July'],
            datasets: [
                {
                    label: 'First Dataset',
                    data: [65, 59, 80, 81, 56, 55, 40],
                    fill: false,
                    borderColor: '#4bc0c0'
                },
                {
                    label: 'Second Dataset',
                    data: [28, 48, 40, 19, 86, 27, 90],
                    fill: false,
                    borderColor: '#565656'
                }
            ]
        };
    }

    ngOnInit() {
    }

    selectData(event) {
        this.msgs = [];
        this.msgs.push({severity: 'info', summary: 'Data Selected', 'detail': this.data.datasets[event.element._datasetIndex].data[event.element._index]});
    }
}

This code snippet showcases a basic line chart, along with a method to fetch data from a REST endpoint. For instance:

ngOnInit() {
    this.http.get('/api/measurements', {responseType: 'json'}).subscribe(data => {
        console.log(data);
    });
}

The JSON response from the endpoint may look like:

{
    "batterStatus": 1,
    "humidity: 15": 15,
    "id": 1,
    "measurementTime": "2017-04-06T06:00:00+02:00",
    "temperatureInside" : 20,
    "temepratureOutside" : 30,
    "weight": 30
}

My goal is to display lines on the chart for:

  • temperature inside
  • temperature outside
  • weight
  • battery status
  • humidity

per time measurement.

I have been struggling with implementing this feature correctly. Any guidance would be highly appreciated.

Answer №1

To represent each measurement as a label and each metric as a dataset, you may need to add an axis for each metric when using PrimeNG. If the datasets are not already in object form, you might have to convert them into an array. Additionally, if compatibility with Edge is a concern, avoid using Object.values and opt for looping through the values instead.

  /**
   * @type {Object} chart configuration. (Consider creating an Interface for this)
   */
  chartData = {
    labels: [],
    datasets: {
      temperatureInside: {
        label: 'Temperature inside',
        data: [],
        fill: false,
        borderColor: '#4bc0c0'
      },
      // repeat for each desired metric
    }
  };

  /**
   * Build the chart's configuration
   * @param {Array} data JSON response data
   */
  buildChartData(data: any[]): any {
    // validate data
    if (!data || data.length < 1) {
      return;
    }

    // iterate through rows (measurements)
    for (const row of data) {
      // add the measurement to the X axis
      this.chartData.labels.push(row.measurementTime);
      // loop through all metrics and save the corresponding value in the dataset
      for (const key of Object.keys(this.chartData.datasets)) {
        // saving the value in the dataset
        this.chartData.datasets[key].data.push(row[key]);
      }
    }

    // convert datasets to an array (might work without this step)
    // NOTE: ES2017 syntax that won't work in Edge
    this.chartData.datasets = Object.values(this.chartData.datasets);
  }

https://stackblitz.com/edit/angular-ywxael?file=app%2Fapp.component.ts

Correction: There is a typo in temepratureOutside that should be fixed...

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

Challenges with inferring return values in Typescript generics

I'm encountering an issue with TypeScript that I'm not sure if it's a bug or an unsupported feature. Here is a Minimal Viable Example (MVE) of the problem: interface ColumnOptions<R> { valueFormatter(params: R): string; valueGette ...

There seems to be an issue with transitioning the React.js page

I'm currently working on managing the page with react-hook, react-router-dom, and redux. The login functionality has been implemented, and I've written the code to redirect to the main page upon successful login. To achieve this, I utilized hi ...

Encountering an issue while trying to execute the command "ionic cordova build android --prod --release

Currently, I am facing an issue while trying to build my apk for deployment on the Play Store. The error message is causing a time constraint and I urgently need to resolve it. Any help or suggestions regarding this matter would be greatly appreciated. ...

Angular date control and its corresponding date panel are not properly aligned on the user interface

I am utilizing Angular and Angular Material for date control display. See the code snippet below: <input type="date" (change)="validateDateRange($event,true, index)" class="form-control oot-start-date align-middle" name=& ...

What is the best method to display a tooltip for a disabled radio button within a set of radio buttons?

Is there a way to disable a specific radio button based on a condition and display a tooltip only for that disabled button? https://i.stack.imgur.com/niZK1.png import {Tooltip} from '@mui/material'; <Tooltip titl ...

The use of URL embedded parameters in @angular/http

Currently, I am utilizing a backend system that accepts search query parameters in both the ?-notation and the url-embedded format. I understand that I can use tools like URLSearchParams/RequestOptionsArgs to send requests to . However, I am curious about ...

Button with circular icon in Ionic 4 placed outside of the toolbar or ion-buttons

Is it possible to create a circular, clear icon-only button without using ion-buttons? I am trying to achieve the same style as an icon-only button within ion-buttons (clear and circular). Here is my current code: <ion-button icon-only shape="round" co ...

Troubleshooting Angular 5 curly brackets problems

Upon updating my app from Angular v2 to v5, I encountered a strange issue with template curly braces. When a template element includes curly braces, nothing would be displayed without any errors in the console. <span>{{ 1 + 1 }}</span> <spa ...

Issue: "contains method is not supported" in Ionic 2

I'm currently working on a code to validate the contents of my input field, but I've encountered an issue with using the contains function. Here's the TypeScript function I have written: checkFnameFunction(name){ if(name.contains("[a-z ...

Technique for transferring information between properties of a class instance within an Express server's architecture

I am in the process of developing a monitoring server for a library using Express. My goal is to create different routers and routes, while also being able to access functions and variables from the monitor-server class. Currently, I have passed the ' ...

Does nestjs support typescript version 3.x?

Currently embarking on a new project using Nestjs. I noticed in one of its sample projects, the version of Typescript being used is 2.8. However, the latest version of Typescript is now 3.2. Can anyone confirm if Nest.js supports version 3.x of Typescrip ...

How to align the markup of a dynamic directive with its host in Angular?

Introducing a simple directive called [popover], its main purpose is to dynamically inject a component (as a sibling). Implementation example: @Component({ selector: 'my-app', template: ` <div> <button popover>Popover ...

What is the best way to authenticate an admin in the front-end using backend technologies like Node.js, Angular, and MongoDB?

Within the user model, there is a property named isAdmin with a default value of false. In MongoDB, I have manually created an admin account with the isAdmin property set to true. When logging in as an admin, the program verifies this and displays "admin ...

What is the best way to load a component every time the function is called?

Currently, I am utilizing Angular and endeavoring to create reusable actions such as bulk updates, deletes, and deactivations. I have incorporated all of these actions into another component and aim to use it as a generic method. This implies that I have ...

In the else-branch, a type guard of "not null" results in resolving to "never."

After creating a type guard that checks for strict equality with null: function isNotNull<T> (arg: T): arg is Exclude<T, null> { return arg !== null } Testing it showed that the then-branch successfully removes null from the type. const va ...

Utilizing Ngrx store for Reacting form validation with the integration of asynchronous validation

I'm currently working on an Angular 8 project where I aim to showcase form errors through NgRx store while utilizing reactive forms with a custom asynchronous validator. login.component.ts @Component({ selector: 'auth-login', templateU ...

Using RouterLink in a div component with Angular's router version 3.0.0-alpha.3

After declaring a div with routerLink, I realized that it was working fine in previous versions but not anymore in (@angular/router 3.0.0-alpha.3). Has anyone found a solution to this issue? <a class="my-item" [routerLink]="['/hero']">... ...

Issue with Angular Filters: Difficulty Arises When Search Box is Cleared

I have a list of objects that I am displaying, and I added a search box to filter a column. When I enter a value, the data is filtered correctly. However, when I clear the search box, I do not get all the data back; I remain stuck with the initially search ...

Exploring the implementation of Chain Map or Chain Filter within an Angular Http request that delivers a promise

I have a dataset in JSON format that I am working with, and I need to filter out specific key values using lodash. I want to reject multiple keys that I don't need. My initial approach is to either chain the map function and then use the reject funct ...

Angular and Bootstrap project with an advanced dropdown menu featuring multiple levels

Looking to create a multi-level drop-down menu using TypeScript without relying on jQuery? Bootstrap CSS framework may not have exactly what you need. https://i.sstatic.net/iruev.png Wondering how to implement a multi-level dropdown in your Angular proje ...