Building Interactive Graphs with Chart.JS in Angular Using Observables

Having some difficulty setting up a Chart with Angular and Chart.JS.

I'm struggling to pass my Observable data into the Chart, no matter what I try.

error TS2339: Property 'cool_data' does not exist on type 'Observable<Object>'.

I suspect that the Observable takes some time to populate with data (roughly 50k data sets), leading to the error because it's empty when the Chart is created. Any suggestions on how to successfully pass my Observable data into the Chart or other solutions?

Here is the Service function I'm currently using:

...
  getData(id: number): Observable<Data[]> {
          return this.http.get<Data[]>(this.dataUrl + id);
                  console.log(this.http.get<Data[]>(this.dataUrl));
                  }
}

And my Component looks like this. I've tried using data: this.data.cool_data but encountered the error mentioned above.

...
data: Data[];
  getData(): void{
  const id = +this.route.snapshot.paramMap.get('id');
        this.coolService.getData(id)
                .subscribe(data => this.data = data);
  }

  goBack(): void{
   this.location.back();
   }


  ngOnInit(): void {
  this.getData();
  }

lineChartData: ChartDataSets[] = [
    { data: this.data.cool_data, label: 'Crude oil prices' },
  ];

  lineChartLabels: Label[] = ['January', 'February', 'March', 'April', 'May', 'June'];

  lineChartOptions = {
    responsive: true,
  };

  lineChartColors: Color[] = [
    {
      borderColor: 'black',
      backgroundColor: 'rgba(255,255,0,0.28)',
    },
  ];

  lineChartLegend = true;
  lineChartPlugins = [];
  lineChartType = 'line';
 }

The HTML template for the component:

<div *ngIf="data">
<div style="display: block;">
  <canvas baseChart width="400" height="400"
    [datasets]="lineChartData"
    [labels]="lineChartLabels"
    [options]="lineChartOptions"
    [colors]="lineChartColors"
    [legend]="lineChartLegend"
    [chartType]="lineChartType"
    [plugins]="lineChartPlugins">
  </canvas>
</div>

Answer №1

After reviewing your input stating that

this.data = [{"id":1,"cool_data":"4.5","station_id":1},{...}]
, it is suggested to utilize the array map function for generating an array of cool_data values. Additionally, the assignment of lineChartData should occur within the HTTP subscription block due to the asynchronous nature of this.data.

Consider implementing the following modifications:

data: Data[];
lineChartData: ChartDataSets[] = [];     // <-- refrain from assigning the value here
lineChartLabels: Label[] = ['January', 'February', 'March', 'April', 'May', 'June'];
lineChartOptions = {
  responsive: true,
};
lineChartColors: Color[] = [
  { borderColor: 'black', backgroundColor: 'rgba(255,255,0,0.28)' },
];
lineChartLegend = true;
lineChartPlugins = [];
lineChartType = 'line';

getData(): void {
  const id = +this.route.snapshot.paramMap.get('id');
  this.coolService.getData(id).subscribe(
    response => {
      this.data = response;
      this.lineChartData.push({             // <-- add value to `lineChartData`
        data: response.map(item => item.cool_data),  
        label: 'Crude oil prices'
      });
    },
    error => { }
  );
}

ngOnInit(): void {
  this.getData();
}

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 Ng4LoadingSpinner will automatically stop after 5 seconds

When utilizing Ng4LoadingSpinner, I encountered an issue where it disappears automatically after the default timeout of 5 seconds, even though our request is still processing. Increasing the timeout resolves the problem, but I am seeking an alternative s ...

Angular 5 and the benefits of concurrent requests

My goal is to execute multiple requests in parallel, fetch the results, and combine them. To achieve this, I have implemented the following function: getStudent(query): Observable<any> { const code = this.http.get( `http://localhost ...

Tips for concealing a dynamic table element in Angular 9

I have dynamically generated columns and rows in a table. Here is my HTML for the table component: <table id="tabella" class="table table-striped table-hover"> <thead class="thead-dark"> <tr> <th *ngFor="let header of _ob ...

Using webpack to generate sourcemaps for converting Typescript to Babel

Sharing code snippets from ts-loader problems may be more suitable in this context: Is there a way to transfer TypeScript sourcemaps to Babel so that the final sourcemap points to the original file rather than the compiled TypeScript one? Let's take ...

What is the best way to organize my NPM package with separate directories for types and functions?

I am currently working on developing a custom NPM package that will serve as a repository for sharing types and functions across my project. Let's name this project wordle. Given the emphasis on types, it is worth noting that I am using TypeScript for ...

Retrieving the return type of generic functions stored in a map

In this unique scenario, I have a dictionary with polymorphic functions that accept the same argument but return different results: const dict = { one: { foo<A>(a: A) { return [a] as const } }, two: { foo<A>(a: A) { ...

What could be causing Typescript to inaccurately infer the type of an array element?

My issue revolves around the object named RollingStockSelectorParams, which includes arrays. I am attempting to have TypeScript automatically determine the type of elements within the specified array additionalRsParams[title]. The main question: why does ...

Angular: Assigning initial value to <select> element

My question relates to a <select> element that is populated from an array as shown below: <select class="form-control form_cbx long-select" formControlName="category" value="Supplier"> <option *ngFor="let cat of userCate ...

Tips for configuring the navigation links on the current page using Bootstrap

In my Angular application, I have set up navigation links for home, about, notifications, and logout. However, when I click on the home link, it redirects me to the login page instead of remaining on the current page. I need the functionality to stay on ...

Improprove performance in Angular by efficiently updating the view through the service

Utilizing the uiSettings service, I am able to control different parts of templates based on user data. Currently, I am directly accessing this service from the template like so: <li *ngIf="uiService.demoButton()"> <button [router ...

Is it possible to enable typescript to build in watch mode with eslint integrated?

Can this be achieved without relying on webpack or other bundlers? Alternatively, is the only solution to have two separate consoles - one for building and another for linting? ...

I am facing an issue with calling a controller from an HTTP GET request in ASP.Net Core 6 using a Single Page Application (SPA) endpoint

[UNSOLVED] - Seeking help from developers [Issue] As a newcomer to the industry, I apologize for my lack of experience in advance. I am currently facing a challenge with ASP.Net Core 6 and it seems like I am missing something simple, but I can't see ...

Using Array.push within a promise chain can produce unexpected results

I have developed a method that is supposed to retrieve a list of devices connected to the network that the client has access to. export const connectedDevicesCore = (vpnId: string, vpnAuthToken: string) => Service.listVPNConnectionsCore ...

What could be causing the elements in my array to appear as undefined?

https://i.stack.imgur.com/ze1tx.png I'm stuck trying to understand why I can't extract data from the array. const usedPlatformLog: Date[] = [] users.forEach(el => { usedPlatformLog.push(el.lastUsed) }) console.log(usedPlatformLog) // disp ...

Can you explain the variance between the (Record<string, unknown>) and object type?

Can you explain the distinction between type Record<string, unkown> and type object? Create a generic DeepReadonly<T> which ensures that every parameter of an object - and its nested objects recursively - is readonly. Here's the type I c ...

The 'items' property cannot be linked to 'virtual-scroller' as it is not a recognized attribute

I'm currently facing an issue with integrating virtual scroll into my Ionic 4 + Angular project. Previously, I relied on Ionic's implementation of virtual scroll (ion-virtual-scroll) which worked well initially. However, I encountered a major dr ...

TypeScript and the Safety of Curried Functions

What is the safest way to type curried functions in typescript? Especially when working with the following example interface Prop { <T, K extends keyof T>(name: K, object: T): T[K]; <K>(name: K): <T>(object: T) => /* ?? */; ...

Implement a uniform CSS design across all elements within an Angular 2 application

I am trying to make use of some basic and reusable CSS rules in my Angular application, such as: .ng-invalid { border-left: 5px solid #a94442; } .ng-valid { border-left: 5px solid #42A948; } However, I want these rules to be applied to all compo ...

EventEmitter is failing to refresh the properties bound with [(ngModel)]

I am currently working with the forms module and Google Maps to update the geocode based on the search box provided on the map. The map is a separate component that emits the Geocode using the function geoCodeChange(). This event is handled by another func ...

MongooseError: Timeout occurred after 10000ms while attempting to buffer the operation `users.findOne()` in a Next.js application

Encountering the "MongooseError: Operation users.findOne() Buffering Timed Out After 10000ms" error in my Next.js app while using Mongoose (^8.2.2) to connect to MongoDB. Using Next.js version 14+ Troubleshooting Steps: 1. Checked MongoDB connection str ...