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

After saving any HTML, SCSS, or TS file, Angular 12 does not compile immediately

Recently I upgraded my Angular project from version 8 to 12 and then migrated to eslint. However, I have encountered an issue where the compilation does not begin immediately after saving a file. There is a delay of approximately 2 minutes before the compi ...

Clicking on the button in Angular 2+ component 1 will open and display component 2

I've been developing a Angular 4 application with a unique layout consisting of a left panel and a right panel. In addition to these panels, there are 2 other components within the application. The left panel component is equipped with buttons while ...

The data from Angular2 Observable Subscription appears undefined, although a closer look at the Browser Debug reveals otherwise

Is it possible there is an issue with the data subscription process? Upon subscribing to data from a service call, 'undefined' is returned as the data set. Surprisingly, when I debug the code in the browser, it clearly shows that the correct dat ...

How can one use an Angular Route to navigate to a distinct URL? Essentially, how does one disable matching in the process?

I'm working on a front-end Angular application and I need to add a menu item that links to an external website. For example, let's say my current website has this URL: And I want the menu item in my app to lead to a completely different website ...

How can the creation of directories for services be avoided in angular-cli?

For those of us using angular-cli, starting from version 1.4, they made the decision to create separate directories not just for components (which is understandable) but also for services that only consist of 2 files: the service file and the test file. ...

A guide on displaying a dynamically generated HTML string as HTML within an Angular 6 framework

I'm having trouble displaying Dynamic HTML (dropdowns) created with TypeScript. When I attempt to show it using innerHTML, the options appear as text instead of a dropdown menu. {{question.question}} <div [innerHTML]="question.question" c ...

Eliminating the most recent entry from the dropdown menu

Currently, I am exploring angular drag and drop functionality in my project. Here is the code snippet that I am using: Link to Code In the implementation, whenever an item is dropped, it automatically goes to the end of the "done" list. What I am looking ...

How can I customize a currency directive in AngularJS using filters?

My goal is to enhance user experience by allowing input in custom currency values like '1.5M' instead of 1500000, and '1B' instead of 1000000000 on an input form dealing with large numbers. To achieve this, I've created a FormatSer ...

Error in Typescript: "Cannot assign to parameter that is of type 'never'"

Here is the code snippet that I am working with: FilesToBlock: []; //defined in this class //within a method of the class this.FilesToBlock = []; this.FilesToBlock.push({file: blockedFile, id: fileID}); However, I'm encountering an issue with fil ...

Certain sections within a Formik form are failing to update as intended

I have successfully implemented a custom TextField wrapper for Material-UI fields, but I am facing an issue with native Material UI fields not updating the form data upon submission. Below is the relevant code snippet along with a link to a code sandbox d ...

What is the best way to input data into the verified full name box?

.html file executed code <input type="name" [(model)]="x.name" class="form-control" pattern="[a-z]" > Greetings to the members of Stack, I am in need of assistance. I am relatively new to Angular and I am looking for a way to validate the full nam ...

Combining two observables into one and returning it may cause Angular guards to malfunction

There are two important services in my Angular 11 project. One is the admin service, which checks if a user is an admin, and the other is a service responsible for fetching CVs to determine if a user has already created one. The main goal is to restrict ac ...

Guide on sending information through a POST request from Angular to a .Net API

My attempt to make a simple request is failing because the value(property) in API is null. Any suggestions on how to troubleshoot this? C# [Route("getpagefields")] [AcceptVerbs(WebRequestMethods.Http.Post)] public IHttpActionResult GetPageFields ...

Are you struggling with perplexing TypeScript error messages caused by a hyphen in the package name?

After creating a JavaScript/TypeScript library, my goal is for it to function as: A global variable when called from either JavaScript or TypeScript Accessible via RequireJS when called from either JavaScript or TypeScript Complete unit test coverage Th ...

What is the best way to modify an object within a pure function in JavaScript?

Currently, I am exploring different strategies to ensure that a function remains pure while depending on object updates. Would creating a deep copy be the only solution? I understand that questions regarding object copying are quite common here. However, ...

Securely transfer data between objects using a for loop

Description I have two similar types that are not identical: type A = { a?: number b?: string c?: boolean } type B = { a?: number b?: string c?: string } I am looking to create an adapter function f() that can convert type A to type B, with ...

What could be causing the error in the console when I try to declare datetime in Ionic?

I am just starting out with Ionic and Angular, but I seem to have hit a roadblock. The compiler is throwing an error that says: node_modules_ionic_core_dist_esm_ion-app_8_entry_js.js:2 TypeError: Cannot destructure property 'month' of '(0 , ...

How can I perform email validation using Angular 6?

I am working on an Angular6 form that includes a field for email input. Currently, the email field has proper validation which displays an error message when an invalid email is entered. However, even if the error message is shown, the form is still saved ...

Steps to resolve the Angular observable error

I am trying to remove the currently logged-in user using a filter method, but I encountered an error: Type 'Subscription' is missing the following properties from type 'Observable[]>': _isScalar, source, operator, lift, and 6 more. ...

What methods does Angular use to display custom HTML tags in IE9/10 without causing any issues for the browser?

Exploring web components and utilizing customElements.define tends to cause issues in IE9/10. I've noticed that Angular is compatible with IE9/10, and upon inspecting the DOM tree, it seems like Angular successfully displays the custom element tags. ...