Utilize Chart.js: invoke a function outside of the onRefresh() method

The code snippet has been attached. In the HomeComponent class, there is a method called rand() that I need to call for the y-axis. However, in the current scenario, this is not possible because when onRefresh() is called, this.rand() is unreachable. This behavior is expected as onRefresh() is called from core.js which is part of the core library. Any assistance on resolving this issue would be greatly appreciated.

export class HomeComponent implements OnInit, OnDestroy {
....
..
options: any = {
scales: {
xAxes: [
{
type: 'realtime',

realtime: {
onRefresh(chart: any) {


chart.data.datasets.forEach(function(dataset: any) {
dataset.data.push({
x: Date.now(),

**y: this.rand()**
});
});
chart.config.options.scales.yAxes[0].ticks.min = chart.helpers.niceNum(20);
chart.config.options.scales.yAxes[0].ticks.max = chart.helpers.niceNum(180);
},

delay: 2000
}
]
},
annotation: {
annotations: [
{
type: 'line',
mode: 'horizontal',
scaleID: 'y-axis-0',
value: '120',
borderColor: 'tomato',
borderWidth: 2
},
{
type: 'line',
mode: 'horizontal',
scaleID: 'y-axis-0',
value: '70',
borderColor: 'blue',
borderWidth: 2
}
]
//drawTime: "afterDraw" // (default)
}
};
....
....

rand(): Number {
return Math.floor(Math.random() * (200 - 100 + 1)) + 100;
}
}

Thank you in advance :)

Answer №1

Considering the way you've coded your rand function, would it not be adequate to employ a similar approach for the X axis data as well?

For instance:

                dataset.data.push({
                  x: Date.now(),
                  y: Math.floor(Math.random() * (200 - 100 + 1)) + 100;
                });

Answer №2

To tackle the issue, one effective approach is to define a global variable outside of the HomeComponent class and then within the constructor of HomeComponent, assign 'this' to this declared variable. This enables seamless access to both methods and instance variables.

Appreciate it!

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

Exploring nested JSON objects with Jade and Express

Currently, I'm feeling a bit frustrated as I struggle to find a way to access the "media" content from this specific JSON object using Jade. { "summary":"Jose Mourinho names his Real Madrid side to face Borussia Dortmund in the Champions Lea ...

Upgrading to Postgres 9.3 for Improved JSON Handling and Date Object Support

Currently working with PostgreSQL 9.3 and exploring options for utilizing TIMESTAMPTZ as authentic JavaScript date objects. Aware of JavaScript lacking a Date literal notation, I considered '{ "key" : new Date(datevalue) }'::JSON as a possibl ...

What is the appropriate way to interpret a POST response in AngularJS?

I'm currently in the process of integrating a payment gateway. Here is the code I have that triggers the request: <form name="ecom" action="https://www.test.com/test/secure/Payment.jsp" method="post"> <input type="hidden" name="requestparame ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

What is the process for setting up Vue.js and using it in conjunction with Sails JS?

After successfully setting up the backend of my website using Sails JS, I decided to integrate Vue.js into my project. Following the installation of Vue and VueResource through npm install --save, I created an app.js file in my assets/js folder. However, ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...

Having difficulty retrieving textbox value through ajax within a php function

There is a text box for weight input where the user can enter the weight and then click a button. Here's the HTML code snippet: <tr> <td> <?php echo "Weight:"; ?> </td> <td> <span class=&ap ...

How is it possible to encounter a Javascript unexpected token ] error within an HTML code?

While working on my project, I encountered a JavaScript error in the console of Chrome. The error message stated "Unexpected token ]" and it was pointing to a specific line of raw HTML code. I am puzzled about what could be causing this issue. Unfortunatel ...

Conflict between Javascript and jQuery plugin discovered in testing environment

I've been trying to implement the smooth scroll functionality from smoothdivscroll.com/#quickdemo on my website, but I'm facing a JavaScript conflict. It seems to work fine on a test page at , but it's not functioning on the live page at viw ...

Conceal the Initial Data Point in a Series on HighCharts

Is there a way to toggle the visibility of specific year columns in a chart using checkboxes? I've tried using the .hide() method but it doesn't seem to work for individual data points within the series. For example, I want to hide the 2018 colum ...

Creating a read-only DIV using Angular - a step-by-step guide

Is there a simple way to make all clickable elements inside a div read only? For example, in the provided HTML code, these divs act like buttons and I want to disable them from being clicked. Any tips or shortcuts to achieve this? Thank you. #html < ...

Is it possible to trigger a function in a component using an array populated with pushed objects?

I have an array of text components that are created using the .push() method: handleWordPress = (i) => { this.setState({selectedWord: this.props.navigation.state.params.meanings[i]}); }; render() { const { params } = this.props.navigation.state; va ...

Unlock the power of Angular JS to display dynamic content effortlessly

My experience with AngularJs is very limited. In one of my projects, I need to display dynamic content on a page that changes based on the database values retrieved via an HTTP GET request. Before implementing the entire functionality, I decided to test i ...

The Position of the WebGL Globe Within the Environment

I've been experimenting with the WebGL Globe, and I have successfully made it rotate. However, I'm struggling to figure out how to adjust its position so that it's not centered in the scene. After making changes to the code found at https:/ ...

Display temperature in the format of '27.0 °C' using either query manipulation or Javascript code

A group of friends and I have embarked on a small IoT project, aiming to control certain aspects via a website accessible on mobile devices. Our main focus is a range slider that adjusts the temperature in a room, with an Arduino managing the actual tempe ...

You are unable to insert a variable within the channels.get() method in discord.js

Attempting to troubleshoot this issue has been quite frustrating. Despite my efforts, it seems that something is not working as expected. I can't help but wonder if I am simply overlooking a simple mistake due to fatigue. Here's the scenario: It ...

"Utilize Angular's $http module to execute a POST request for

Hey everyone, I'm a beginner with AngularJS and I've run into a problem while working on my project. I encountered this error: ReferenceError: $http is not defined when attempting to utilize the following code: 'use strict'; ...

Ways to include a line break in the message of a fresh Error instance in JavaScript

I have a function within a service structured like this: The Policies array contains functions that will throw an error if a policy is violated (e.g. password missing numbers or capital letters). function myFunction(policies, password){ var policiesE ...

The functionality of $(selector).css() seems to be malfunctioning

I currently have an html div element stored in a variable var rows = ""; rows += "<div>1111 : Hi there</div>"; Despite multiple attempts, I have failed to add a background color to this div using the following methods: 1. $(rows).css({&apos ...

Navigating through 'ui-router' to a specific state depending on the user's

Is it possible to redirect a user to a particular state using data from cookies with ui-router? I attempted to accomplish this within the .config() function but encountered issues due to the inability to inject additional dependencies. Another approach I ...