Attempting to create a bar graph using Angular framework

I'm currently working on developing a dashboard in Angular that includes a chart feature. Within my Firebase Firestore database, I have two collections: 'mechanicQualifications' and 'mecanicos'. The 'mechanicQualifications' collection contains ratings given to mechanics by users. The specific chart I am trying to create is a bar chart that illustrates the average rating for each mechanic.

However, I have encountered an issue where the chart only displays mechanic IDs instead of their names. I am attempting to retrieve the mechanic names based on their IDs from the 'mechanicQualifications' collection, but it seems to only display '0' rather than the actual mechanic names.

Any suggestions on how I could resolve this problem?

https://i.sstatic.net/5QLzh.png

Here is the relevant code:

mechanicRatings: { mechanicId: string, qualification: number }[] = [];
interface MechanicQualification {
  mechanicId: string;
  qualification: number;
}
this.firestore.collection<MechanicQualification>('mechanicQualifications')
.valueChanges()
.subscribe(qualifications => {
  const mechanicRatingsMap: { [mechanicId: string]: number[] } = {};
  qualifications.forEach(qualification => {
    if (!mechanicRatingsMap[qualification.mechanicId]) {
      mechanicRatingsMap[qualification.mechanicId] = [];
    }
    mechanicRatingsMap[qualification.mechanicId].push(qualification.qualification);
  });
  this.mechanicRatings = Object.keys(mechanicRatingsMap).map(mechanicId => {
    const ratings = mechanicRatingsMap[mechanicId];
    const qualification = ratings.reduce((acc, rating) => acc + rating, 0) / ratings.length;
    return { mechanicId, qualification };
  });
});
  this.firestore.collection('mecanicos').get().subscribe(snapshot => {
    const mechanicNames: { [mechanicId: string]: string } = {};
    snapshot.forEach(doc => {
      const mechanicData = doc.data() as { uid: string, name: string };
      mechanicNames[mechanicData.uid] = mechanicData.name;
    });

    const chartData = this.mechanicRatings.map(item => ({
      name: mechanicNames[item.mechanicId],
      y: item.qualification
    }));

    this.createBarChart(chartData);
  });

And this is how I go about creating the chart:

createBarChart(chartData: { name: string; y: number }[]) {
  const chartOptions: Highcharts.Options = {
    chart: {
      type: 'bar'
    },
    title: {
      text: 'Average Mechanic Ratings'
    },
    xAxis: {
      type: 'category',
      title: {
        text: 'Mechanic Name' 
      }
    },
    yAxis: {
      title: {
        text: 'Average Rating'
      }
    },
    series: [{
      name: 'Average Rating',
      type: 'bar',
      data: chartData
    }]
  };
  Highcharts.chart('rating-container', chartOptions);
}

Answer №1

One way to enhance the visualization is by incorporating categories and labels on the xAxis.

xAxis: {
 type: 'category',
 title: {
   text: 'Mechanic Name' 
 },
 categories: chartData.map(item => { return item.name });
 labels: {
   enabled: true
 }
}

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 Jest worker has run into 4 child process errors, surpassing the maximum retry threshold

I am a newcomer to Vue and Jest testing, and I keep encountering this error when running a specific test. While I understand that this is a common issue, I am struggling to pinpoint the exact cause of the problem. Here is the error message: Test suite fa ...

[attr.disabled]="isChecked ? '' : 'disabled'"

[attr.disabled]="isChecked == true ? '' : disabled" Can anyone assist me with disabling unchecked checkboxes in a loop using Angular 8? [attr.disabled]="isChecked == true ? '' : disabled". Need help with this in Ang ...

Implementing dynamic validation rules in Angular forms

In my code, there is a part where I need to make certain fields required. Initially, only the emailAddress field is required, but under a specific condition (res.isSuccess === true), I also need to set firstName, lastName, and companyName as required. The ...

Angular - Bootstrap 5 Slidehow is malfunctioning

I'm having trouble with the Bootstrap Carousel in Angular (17). The Previous & Next buttons don't seem to be working as expected. The carousel seems to be stuck on the first image and I'm not getting any errors in the console. I've ...

Ways to determine the generic type of a property value from a decorated property within a decorator

While experimenting with some code, I encountered an issue where the generic type of a property value wasn't being resolved correctly when changing from TValue to (t: TValue) => TValue. Instead of being recognized as the expected number, it was now ...

troubleshooting angular universal with HTTPS

My angular universal app is all set up and running smoothly for POST requests on the server-side using localhost to pre-render my app. An example of a working URL would be http://localhost:8000/api/get-info. However, things took a turn when I deployed the ...

Angular feature: Utilizing the @Output decorator for subscribing to EventEmitter

I have created a custom directive featuring an @Output EventEmitter: @Directive({ selector: '[ifValid]' }) export class SubmitValidationDirective { @Output('ifValid') valid = new EventEmitter<void>(); constructor( ...

Unable to render an array retrieved from a GET request in Angular 2

After fetching an array from mongodb, I am trying to display it on the template. However, even though the response with articles is received (as shown in the Chrome network tool), the articles are not being rendered on the page. Below is the code snippet ...

Angular location services

I'm experiencing some difficulties with the geolocation feature. It works fine when the user clicks allow, but there's an issue when using If else. If the user clicks deny, it doesn't insert into the else block. You can check out this DEMO f ...

What are some techniques for breaking down or streamlining typescript code structures?

Within my TypeScript class, I have a skip function. In the interface, I've specified that the data is coming from the backend. Now, on the frontend, I want to be able to rename the backend variables as demonstrated below. There are multiple variables ...

Transferring css to an external file within an angular 4 component by utilizing webpack

I encountered this specific error message: Error: Anticipated 'styles' to be a collection of strings. Despite the fact that I have clearly defined the styles as an array of strings: styleUrls: ['./app.component.css'] Can anyone pinp ...

Utilizing the useSearchParams() function to retrieve live data in Next.js

Is there anyone who has successfully migrated from the pages router to the app router in Next.js? I am facing an issue with dynamic data migration. In the pages router, dynamic data is retrieved on a page using useRouter().query, but in the app router, it ...

How to access the types of parameters in a function type

I am working on a function that takes a value and default value as arguments. If the value is a boolean, I want the return type to match the type of the default value. Here is the function I have: export type DetermineStyledValue<T> = ( value: str ...

Retrieving a specific user attribute from the database using Angular

Currently, I am working on developing an application that utilizes ASP.NET for the Back End (API) and Angular for the Front End of the application. Within the API, I have set up controllers to retrieve either a list of users from the database or a single ...

specialized registration process with auth0 in Angular

I am attempting to enhance the user information in a single call. The process involves first signing up with a username and password on Auth0, followed by adding additional userinfo to the database during the callback phase. However, I am encountering diff ...

Angular 8 form controls becoming unresponsive while the list is being loaded

Hello, I am currently experiencing an issue in Angular. I have a page with a basic Angular form and two independent components that load lists from an API (comments with 500+ records and posts with 500+ records). The Problem: While trying to enter values ...

How to Guarantee NSwag & Extension Code is Positioned at the Beginning of the File

In my project, I am using an ASP.Net Core 3.1 backend and a Typescript 3.8 front end. I have been trying to configure NSwag to include authorization headers by following the guidelines provided in this documentation: https://github.com/RicoSuter/NSwag/wik ...

What ways can I dynamically implement styles using ngStyle in Angular?

Is there a way to toggle the position value from left to right based on a boolean condition? I am looking to switch [ngStyle]="{ 'left.px': offSetX } with [ngStyle]="{ 'right.px': offSetX } depending on a certain condition import { C ...

Angular implementation of reverse geocoding

retrieveAddress(lat: number, lng: number) { console.log('Locating Address'); if (navigator.geolocation) { let geocoder = new google.maps.Geocoder(); let latlng = new google.maps.LatLng(lat, lng); let request = { LatLng: latlng }; ...

Customizing primary button colors in Bootstrap 5.2

I've been attempting to customize the default colors in Bootstrap 5.2.3 within my Angular 15 application, specifically to make .btn-primary reflect my app's primary color, but so far I haven't been successful. Here's a snippet from my ...