Tips for sending asynchronous data to Google-Charts-Angular

I am currently working on generating a chart using data obtained from an API call. To achieve this, I am utilizing the google-charts-angular package within my HTML:

<google-chart [title]="title" [type]="type" [data]="data"  [options]="options"></google-chart>

My main objective is to pass the fetched data to the chart. This process is handled in my component.ts file. Initially, I tested it with randomly created data:

title = 'Issues';
  type = 'Gantt';
  data = [
    ['1', 'Read', 'whatever', //More data ....],
    ['2', 'Write', 'whatever', // More data ...,
  ];
  columnNames = [
    ['string', 'Task ID'],
    ['string', 'Task Name'],
    ['string', 'Resource'],
    // More columns ...
  ];

The above setup works as expected. Moving forward, I intend to utilize data retrieved from the API. The GetIssues function returns an Observable through the http.get() method:

ngOnInit(): void {
  this.apiService.getIssues().subscribe(response => {})
}

However, I am encountering difficulty in passing asynchronously retrieved data from the subscription to the chart. My attempt to add new arrays to the data array using push did not yield the desired outcome:

issues = [];
data = [
    ['1', 'Read', 'whatever', new Date(2015, 0, 1), new Date(2015, 0, 3),  1, 100, null],
    ['2', 'Write', 'whatever', new Date(2015, 0, 4), new Date(2015, 0, 7),  1, 100, null],
  ];
      ngOnInit(): void {
        this.apiService.getIssues().subscribe(response => {
          this.issues = response;
          if (this.issues) {
            let id = 3;
            for (let issue of this.issues) {
              this.data.push([id, issue.title, 'whatever', new Date(2015, 0, 4), new Date(2015, 0, 7),  1, 100, null]);
              id += 1;
            }
          }
        });
      }

It appears that the chart displays the two predefined arrays in "data," but fails to show the new arrays added via push. This issue may be attributed to the chart being rendered before the asynchronous operation completes. If indeed this is the root cause, I am uncertain about how to trigger the chart rendering post completion of the asynchronous task.

Answer №1

After some troubleshooting, I managed to find a solution:

  ngOnInit(): void {
    this.issues = this.apiService.getIssues();
    this.issues.subscribe(response => {
      this.data.push( ['1', response[0].title, 'whatever', new Date(2015, 0, 4), new Date(2015, 0, 7), 1, 100, null]);
    })
  }

Implementation in the template:

<div *ngIf="issues | async">
    <google-chart [title]="title" [type]="type" [data]="data" [options]="options"></google-chart>
</div>

To summarize my approach:

  1. The Http.get method returns an Observable, which I store in a variable named issues
  2. I use *ngIf in the template to verify the existence of issues
  3. By piping to async within *ngIf, I ensure it waits for the Observable to return data
  4. Subsequently, I subscribe to issues and selectively push necessary values into the data array

However, I am unsure if this method is optimal or if it may pose potential issues.

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

ReactJS Error: The property 'hubConnection' is not defined on type 'JQueryStatic'

I am currently working with the Signalr library in React, but I keep encountering the following error: Property 'hubConnection' does not exist on type 'JQueryStatic'. Is there a solution to this issue? declare var window : any; import ...

What is the process for deploying a Lambda function using Terraform that has been generated with CDKTF

Currently, I am following a tutorial by hashicorp found at this link. The guide suggests using s3 for lambda deployment packages. // in the process of creating Lambda executable const asset = new TerraformAsset(this, "lambda-asset", { ...

Material UI is not capable of utilizing Props

I'm having trouble using the Checkbox component from Material UI. Even though I can't seem to use the normal props like defaultChecked or size="small", as it gives me the error TS2769: No overload matches this call. TS2769: No overload ...

Modifying an onClick handler function within a react element located in a node module, which points to a function in a prop declared in the main Component file

I have successfully implemented the coreui CDataTable to display a table. return ( <CDataTable items={data} fields={fields} ... /> ) Everything is working smoothly, but I wanted to add an extra button in the header of the C ...

Angular 12 - Directing users to different views depending on their roles

In my situation, the Admin role login will be able to access the Home and UserView Component. After logging in, an Admin will automatically be taken to the Home component. On the other hand, the User role login will only have access to the UserView compone ...

How to eliminate certain elements from the DOM in Angular 5

I'm facing a minor issue in my Angular/Typescript project that I can't seem to resolve. I am still new to these technologies and struggling with removing certain DOM elements. The content is auto-generated with specific CSS classes, and unfortuna ...

Advantages of passing individual variables instead of the entire object from HTML to JavaScript in AngularJS

When it comes to passing the iterating object from HTML to Javascript, there are two approaches that can be taken. The first approach involves passing the iterating object as a whole, while the second approach only passes the required properties of the obj ...

What is the best way to set up an empty {[key: string]: string} object in TypeScript?

interface a { d: {[key: string]: string} } class a { d = {} } The error message returned is as follows: Subsequent property declarations must have the same type. Property 'd' must be of type '{ [key: string]: string; }', but ...

Creating types for React.ComponentType<P> in Material-UI using TypeScript

I am currently working with Typescript and incorporating Material-UI into my project. I am trying to define the component type for a variable as shown below: import MoreVert from '@material-ui/icons/MoreVert' import { SvgIconProps } from '@ ...

Unraveling the mysteries of Typescript with async await

I'm facing a peculiar issue in my code that I'm struggling to identify. try { const result = await somePromise.catch((err) => { console.log(new Date()); // displays time, t0 console.log('Stats', eventLoopStats.se ...

What is the best method for accurately capturing time-stamps from web users using Angular 2?

Is there a more accurate way to obtain timestamps in Angular 2 from my website users? Currently, I am collecting timestamps using the simple JavaScript code Date.now(), but some users may have incorrect system dates leading to inaccurate timestamps. What ...

What is the best way to utilize RxJs for streaming HostListener events?

Although I've found plenty of resources on binding Angular HostListeners, I'm curious about using RxJs to stream it instead: @HostListener('document:click', ['$event']) handleClick(event: Event) { // etc } I want to cre ...

What's causing the "* before initialization" error in Vue with TypeScript?

I am encountering an issue with my code where I get the error "Cannot access 'AuthCallback' before initialization" when attempting to call the router function in the AuthCallback component. What could be causing this problem? The desired function ...

Trigger a modal from one sibling Angular component to another

My application utilizes an Angular6 component architecture with the following components: <app-navbar></app-navbar> <app-dashboard></app-dashboard> The Dashboard component consists of: <app-meseros> </app-meseros> < ...

How to implement a toggle button in an Angular 2 application with TypeScript

Currently, I'm working with angular2 in conjunction with typescript. Does anyone know how to generate a toggle button using on - off?. ...

Issue with Angular 8 docker container: module not found despite being installed

I am currently working on an Angular 8 single-page application (SPA). Utilizing a Dockerfile that is managed and executed through a Docker Compose setup. Everything was functioning smoothly for weeks until today when, out of nowhere, the setup stopped wor ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

Detecting incorrect serialized data entries based on data types

In the scenario where the type MyRequest specifies the requirement of the ID attribute, the function process is still capable of defining a variable of type MyRequest even in the absence of the ID attribute: export type MyRequest = { ID: string, ...

Sequelize Date Range Error When Using Op.between with TypeScript

My goal is to retrieve all records from a MySql table that were created within a specific date range. To accomplish this, I created the following code snippet: import { Sequelize, Model, DataTypes, Op } from 'sequelize'; const sequelize = new ...

Is there a way to obtain the coordinates of an SVG element by simply clicking on a specific point?

I'm still learning about SVG and I'm trying to trigger an event that captures the click coordinates when clicking on the SVG. I have a few questions: Since I'm using Angular, I'm unsure if it's possible to keep my function in th ...