Create a Bar Graph Using a List

Looking to generate an Angular Barchart from a JPA query in Spring:

public List<PaymentTransactionsDailyFacts> findPaymentTransactionsDailyFacts(LocalDateTime start_date, LocalDateTime end_date) {

    String hql = "SELECT SUM(amount) AS sum_volume, COUNT(*) AS sum_Transactions " + 
            " WHERE (created_at BETWEEN :start_date AND :end_date )" + 
            " GROUP BY DATE(created_at)";

    TypedQuery<PaymentTransactionsDailyFacts> query = entityManager.createQuery(hql,
            PaymentTransactionsDailyFacts.class).setParameter("start_date", start_date).setParameter("end_date", end_date);
    List<PaymentTransactionsDailyFacts> data = query.getResultList();
    return data;
}

Desired output of the query:

Date       | Amount| Number of transactions per day |
11-11-2018 | 30    | 3                              |
11-12-2018 | 230   | 13                             |

Object mapped from JPA query:

public class DashboardDTO {

private Date date;

private int sum_volume;

private int sum_Transactions;

... getters and setters
}

Angular Service:

@Injectable({
  providedIn: 'root'
})
export class DashboardService {

constructor(private http: HttpClient) {
}

getCurruncyList(): Observable<Array<CurruncyList>> {
return this.http.get<Array<CurruncyList>>(environment.api.urls.dashboard.getVolumes);
}
}

Interface

export interface CurruncyList {
date: Date,
amount: number,
number_of_transactions: number
}

Dashboard component with Barchart:

selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

barData: any;

constructor() {
}

ngOnInit() {
this.barChart();
}


barChart() {
this.barData = {
labels: ['02-10-2018', '03-10-2018', '04-10-2018', '05-10-2018', '06-10-2018', '07-10-2018', '08-10-2018'],
datasets: [
{
label: 'USD',
backgroundColor: '#42A5F5',
borderColor: '#1E88E5',
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: 'EUR',
backgroundColor: '#9CCC65',
borderColor: '#7CB342',
data: [28, 48, 40, 19, 86, 27, 90]
}   
]
}
}
}

How can I create a Barchant using <Array<CurruncyList>? Utilizing the database query mentioned above within the provided code.

Update: tested example:

import {Component, OnInit} from '@angular/core';
import {DashboardService} from "../service/dashboard.service";

@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

barData: any;

constructor(private dashboardService: DashboardService) {
}

ngOnInit() {
this.barChart();
}

barChart(){
this.dashboardService.getCurruncyList().subscribe(data => {
this.barData = data.map(t => t.date);
response.map(function (o) {
  return {
    data: 22,
    label: o.date
  };
});
});

} }

Answer №1

To successfully display the dataLabels in your component, make sure to subscribe and utilize Array.map for generating them. Here is an example implementation:

constructor(private dashboardService : ChartDataService)

renderChart(){
  this.dashboardService.getCurrencyList().subscribe(response=>{
       this.dataLabels = response.map(item=> item.date);
       response.map(function (obj) {
          return {
            data: // include transactions count here
            label: obj.date
          };
  });
}

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

Tips on how to use Selenium and Java to successfully click on the "logout" link in HTML

Below is the code snippet: <div id="user-tools"> Welcome <strong>Admin</strong> / <a href="/">View</a> / <a href="/admin/password_change">Change password</a> / </a href="/admin/l ...

Using Typescript, the type T or a function that returns T can be utilized in various scenarios

You can check out a demonstration on this interactive platform. In creating a simple generic type that represents either a variable or a function returning a variable, there was an issue with the typical typeof arg === 'function' check. The erro ...

Extract keys from a list of interface keys to create a sub-list based on the type of value

Issue Can the keys that map to a specified value type be extracted from a TypeScript interface treated as a map? For example, consider the WindowEventMap in lib.dom.d.ts... interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHan ...

Ways to print several tabs at once in Angular 4

In my Angular 4 application, I have implemented a feature with 4 tabs ('tab1', 'tab2', 'tab3', 'tab4') on the screen. Each tab corresponds to an Angular component that is dynamically loaded. When a user lands on the ...

Tips for transferring information between concatMap operators in RXJS in an Angular application

I am working with an observable pipe that looks like this: .pipe( concatMap(() => this.security.getUser()), tap((partyId) => { if (!partyId) { window.location.assign(`${environment.redirectURL1}/dashboard/login`); } }), concatMap( ...

Dispatch a websocket communication from a synchronous function and retrieve the information within the function itself

I am currently working on an Angular project and need guidance on the most effective approach to implement the following. The requirement is: To retrieve an image from the cache if available, otherwise fetch it from a web socket server. I have managed ...

Using TypeScript and webpack, include the access_token in the http header when making requests with axios

I need to include an access_token in the header of axios, following this example: https://github.com/axios/axios#global-axios-defaults Currently, I am fetching the access_token using razor syntax, which is only accessible in CSHTML files. https://github ...

Obtaining the dimensions of each individual child component within an NgTemplate

I have the following code snippet within my template. While I can iterate through its components using `get`, it does not return an object that allows me to access deeper into the HTML attributes. <ng-template #container></ng-template> Compon ...

filter failing to provide output

Issue with fetching partnername from the filter function, always returning undefined. administrationList = [ { "runid": 6, "partnerid": 2, "partnername": "test admin2", }, { "runid& ...

AngularJS is failing to properly register custom directives

Looking to enhance the SEO caching capabilities of my AngularJS website, I've embarked on implementing a couple of directives for custom page titles and descriptions. Incorporated within my app config (angular.module('website', [...'we ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

Changing the function to operate asynchronously

How can I convert the following code into an asynchronous function? It is currently returning referralUrl as undefined: controller async createReferralUrls() { this.referralUrl = await this.referralService.generateReferralUrl(this.userData.referral ...

I'm struggling to find a solution to this pesky TypeScript error that keeps popping up in the button component's styling. How can

An error related to style is appearing: <Button style = No overload matches this call. Overload 1 of 3, '(props: { href : string; } & { children?: React Node; classes?: Partial<Button Classes> | undefined; color?: "primary" | ...

Clicking the "X" close button on a mat-list removes an item from the user interface

Recently, I utilized the mat-list component to display items on the UI. Each item is accompanied by a close(X) button located on the right-hand side. https://i.stack.imgur.com/1E2ZG.png Html Code <mat-list > <ng-container *ngFor='le ...

Retrieving information from a JSON file utilizing an Interface

For the purpose of learning, I am developing a small Ionic app where I want to load data from a JSON file and map it to an interface that defines the data structure. However, I am facing challenges in achieving this: import { Component } from "@angular/co ...

Can you explain the reference to "ng2" in relation to Angular 2?

In countless blog posts discussing Angular 2, I often come across references to ng2. Can someone clarify what ng2 stands for? Is it the CLI for Angular 2? ...

"I seem to be encountering a problem where I am only able to retrieve the

I have a task that involves retrieving search results of users, with each user represented as an object containing attributes like name, lastName, and title. The goal is to create a list of these objects and perform certain actions on them. I have encounte ...

Webpack does not support d3-tip in its current configuration

I'm having some trouble getting d3-tip to work with webpack while using TypeScript. Whenever I try to trigger mouseover events, I get an error saying "Uncaught TypeError: Cannot read property 'target' of null". This issue arises because th ...

formik connects props that are lacking certain properties

Trying to figure out a way to simplify the process of declaring all the properties of formik in my Props when using connect(). The error message I keep encountering is: Type '{ entry: Entry; }' is missing the following properties from type &apos ...

Mastering the Conversion from NGRX Effect to NGRX Effect v15

I am currently working on converting the code snippet to NGRX 15. As a newcomer to Angular, I could use some guidance. "@ngrx/effects": "^15.4.0" @Injectable() export class SnackbarEffects { @Effect({ dispatch: false }) cl ...