What is the correct way to utilize a class variable within the function() method?

Class Variable Name: addPointY

Utilizing "addPointY" in a Function:

setInterval(function () {
    var y = Math.round(Math.random() * 100);
    series.addPoint(this.addPointY, true, true);
}, 3000);

I am tasked with finding a solution for this. It is a customer requirement that remains unresolved. Please suggest an alternative approach.

The class variable must be utilized in one of its methods. However, I am struggling to access the class variable.

Is there a skilled developer who has successfully tackled the same issue?


@Injectable()
export class HighChartService implements ChartService {
private addPointY: number = 0;

shiftAddPoint(data: number) {
    this.addPointY = data;
    console.log(this.addPointY);
}

/**
* @see DynamicChart start function
* @param obj chart Object
* @param title Top Title
* @param type ChartType
* @param yAxisTitle Left Title
* @param series Chart data
* @author jskang
* @since  2017/10/12
*/
dynamicInitOptions(title: string, type: string, yAxisTitle: string, series: Object[]) {
    if (!type) { type = "line"; }
    let obj = new Chart({
        chart: {
            type: type,
            events: {
                load: function () {
                    var series = this.series[0];
                    setInterval(function () {
                        var y = Math.round(Math.random() * 100);
                        series.addPoint(this.addPointY, true, true);
                    }, 3000);
                }
            }
        },
        title: { text: title },
        xAxis: {
            categories: [0,1,2,3,4,5,6],
            labels: {
                formatter: function () {
                    let xAxis = "";
                    if(this.value % 7 == 0){ xAxis = "일"; }
                    else if(this.value % 7 == 1){ xAxis = "월"; }
                    else if(this.value % 7 == 2){ xAxis = "화"; }
                    else if(this.value % 7 == 3){ xAxis = "수"; }
                    else if(this.value % 7 == 4){ xAxis = "목"; }
                    else if(this.value % 7 == 5){ xAxis = "금"; }
                    else if(this.value % 7 == 6){ xAxis = "토"; }
                    return xAxis;
                }
            }
        },
        yAxis: {
            title: {
                text: yAxisTitle
            },
            labels: {
                formatter: function () {
                    return this.value;
                }
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle'
        },
        series: series
    });
    return obj;
}

}

Answer №1

If you are struggling with the this reference inside your callback function when using setInterval, it's because the traditional function () {} syntax creates its own binding for this.

One solution is to switch to arrow functions, which maintain the context and allow you to access your class properties seamlessly within the callback:

load: () => { // Arrow function preserves `this`
    // set up the updating of the chart each second
    var series = this.series[0];
    setInterval(() => { // Arrow function for callback
        var y = Math.round(Math.random() * 100);
        series.addPoint(this.addPointY, true, true);
    }, 3000);
}

Alternatively, you can implement the that pattern by storing your class instance reference in a variable and using it whenever you need to refer to your instance:

dynamicInitOptions(title: string, type: string, yAxisTitle: string, series: Object[]) {
    if (!type) { type = "line"; }
    let that = this; // Store `this` in `that`
    let obj = new Chart({
        chart: {
            type: type,
            events: {
                load: function () {
                    // set up the updating of the chart each second
                    var series = this.series[0];
                    setInterval(function () {
                        var y = Math.round(Math.random() * 100);
                        series.addPoint(that.addPointY, true, true); // Use `that` instead of `this` here
                    }, 3000);
                }
            }
        }
        // ...
    });
}

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

Must run the angular code in a sequential order

I need to run the code in a specific order; first the foreach loop should be executed, followed by a call to the getHistory() method. Your assistance is greatly appreciated. const execute = async()=>{ await this.currentContent.forEach(async ...

The implementation of combineSlices in reduxjs/[email protected] is an essential feature for managing

I am struggling to figure out how to properly useAppSelector with LazyLoadedSlices: Here is the setup of my store // @shared/redux/store.ts // comment: https://redux-toolkit.js.org/api/combineSlices // eslint-disable-next-line @typescript-eslint/no-empty ...

I encountered an issue while generating a crypto address on the Waves blockchain using the @waves/waves-crypto library in TypeScript

Encountering an issue with finding "crypto-js" in "@waves/waves-crypto". Despite attempts to uninstall and reinstall the module via npm and importing it using "*wavesCrypto", the error persists within the module's index.d.ts file. I am attempting to ...

What is the best method for determining the centroid of a set of points in the R programming

In the programming language Python, you may work with a list of lists, for example: lst = [[0, 1, 2], [2, 3, 4]]. To find the centroid within this data structure, one could implement the following code: n = len(lst[0]) centroid = [0]*n def centroid(*args ...

Generating a JSON list from a Map object utilizing an interface in Angular 9

The map in my project is generated using the countries-map plugin and includes data values. Here is an example of the data provided by the plugin: mapData: CountriesData = { 'ES': { 'value': 416 }, 'GB': { 'value&apos ...

Issue with Jest/SuperTest Express integration tests: encountering "Can't set headers after they are sent" error when making requests to the same endpoint in multiple test cases

Dealing with a tricky situation here.. I'm currently in the process of writing integration tests for an Express (Typescript) app, using Jest and Supertest. My challenge lies in having multiple tests for the same endpoint, specifically to test respon ...

Angular - Set value on formArrayName

I'm currently working on a form that contains an array of strings. Every time I try to add a new element to the list, I encounter an issue when using setValue to set values in the array. The following error is displayed: <button (click)="addNewCom ...

Discovering the JavaScript source file for a package using WebStorm and TypeScript

In my TypeScript project, there is a usage of Express with the following method: response.send('Hello'); I am interested in exploring the implementation of the send() method. However, when I try to navigate to the source code by ctrl+clicking o ...

What is the recommended approach for sending a null value to a mandatory property in a Vue.js component?

Setup: Vue.js (3.2) with Composition API, TypeScript, and Visual Studio Code File type.ts: export class GeographicCoordinate { latitude: number; longitude: number; altitude?: number; constructor(latitude: number, longitude: number, altitude?: num ...

Only one argument is accepted by the constructor of NGRX data EntityServicesBase

In an attempt to enhance the convenience of my application class, I decided to create a Sub-class EntityServices based on the NGRX/data documentation which can be found here. Despite following the provided example, it appears that it does not function pro ...

Proper method of managing undeclared declaration files (index.d.ts)

I encountered the following error message: error TS7016: Could not find a declaration file for module 'react-native-camera'. '/Users/ilja/Documents/Repositories/blok/node_modules/react-native-camera/index.js' implicitly has an 'an ...

The function 'toLowerCase' cannot be found for the type 'string | number | string[]'. Similarly, the function 'toLowerCase' cannot be found for the type 'number'

Currently, I am working on a Laravel project using Laravel Mix. I am attempting to create a table with filter functionality. However, when I insert the following code into my TS file: import $ from 'jquery'; import 'bootstrap'; $(() = ...

Display an image on an HTML page based on the TypeScript data in an Ionic Angular application

After retrieving user profile data from the database and storing it in an observable, I am able to access properties such as profileData.username, profileData.msgnumber, and more. When profileData.avatar returns the name of the avatar the user is using, I ...

Is it possible to efficiently share sessionStorage among multiple tabs in Angular 2 and access it right away?

My Current Knowledge: I have discovered a way to share sessionStorage between browser tabs by using the solution provided here: browser sessionStorage. share between tabs? Tools I Am Using: Angular 2 (v2.4.4) with TypeScript on Angular CLI base The ...

Employing Typescript types in array notation for objects

Can someone please help me decipher this code snippet I found in a file? I'm completely lost as to what it is trying to accomplish. const user = rowData as NonNullable<ApiResult["getUsers"]["data"][number]["users"]> ...

Tips for sending properties to a child component in a React Native project using TypeScript

Here is the setup in my parent component: const [OTPNotify, setOTPNotify] = useState("flex"); const closeOTPNotify = () => { setOTPNotify("none"); } <OTPRibbonComponent onCancel={closeOTPNotify} display={OTPNotify}/> Now, ...

Utilize Typescript to ensure uniformity in object structure across two choices

Looking to create a tab component that can display tabs either with icons or plain text. Instead of passing in the variant, I am considering using Typescript to verify if any of the icons have an attribute called iconName. If one icon has it, then all othe ...

How can I implement a scroll bar in Angular?

I am facing an issue with my dialog box where the expansion panel on the left side of the column is causing Item 3 to go missing or appear underneath the left column when I expand the last header. I am looking for a solution to add a scroll bar so that it ...

Double-tap bug with Image Picker in Typescript React Native (non-expo)

Well, here’s the situation - some good news and some bad news. First, the good news is that the code below is functioning smoothly. Now, the not-so-good news is that I find myself having to select the image twice before it actually shows up on the clie ...

Is it possible to omit certain fields when using the select function in MikroORM?

When working with nested populate queries in MikroORM with MySQL, I am faced with the challenge of selecting 100 fields while wanting to exclude around 20 fields. It would make more sense to leave out those 20 fields, similar to using db.find().select("- ...