Unable to access data within the function in Typescript

In my TypeScript code, I've encountered an issue where the `copyColumns` data is not accessible inside a recursive function named `rec`, despite being accessible outside of it. Can someone help me identify what's wrong in my code?

When I run console.log(this.copyColummns);, it returns undefined.

copyNodeHandler ( column, node ) {
            this.copyHeaders = [];
            this.copyHeadersDeepCopy = [];
            for ( let i = 0; i < node[ 0 ].values.length; i++ ) {
                this.copyHeaders.push(node[ 0 ].values[ i ].parameterId)
            }
            this.copyColumns = node;
        }

setBinary(rowId, vId, data) {          


console.log(this.copyColumns); // This prints fine

    let rec = function (pri, pvi) {
        console.log(pri + '' + pvi);
        console.log(this.copyColumns); // This does not work and returns undefined.
        let latest = [];           
        if (this.copyColumns[pri]) {
            this.copyColumns[pri].values[pvi].active = true;          

           let  x = this.copyColumns[pri].values[pvi]
            rec(x.pri, x.pvi)
        }
    };


    rec(data.pri, data.pvi)

}

Answer №1

When you create a new function in javascript, it establishes a new scope.

Two common approaches to maintaining the scope of the function are using arrow functions or binding(this) to the function.

First Approach:

           // arrow function
let rec = (pri, pvi) => {
    console.log(pri + '' + pvi);
    console.log(this.copyColumns); // The copyColumns reference will remain consistent inside and outside the function
    let latest = [];           
    if (this.copyColumns[pri]) {
        this.copyColumns[pri].values[pvi].active = true;          

       let  x = this.copyColumns[pri].values[pvi]
        rec(x.pri, x.pvi)
    }
};

Second Approach:

let rec = function (pri, pvi) {
    console.log(pri + '' + pvi);
    console.log(this.copyColumns); // Not effective as it returns undefined.
    let latest = [];           
    if (this.copyColumns[pri]) {
        this.copyColumns[pri].values[pvi].active = true;          

       let  x = this.copyColumns[pri].values[pvi]
        rec(x.pri, x.pvi)
    }
// bind this to the function
}.bind(this);

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

Error: The "res.json" method is not defined in CustomerComponent

FetchData(){ this.http.get("http://localhost:3000/Customers") .subscribe(data=>this.OnSuccess(data),data=>this.OnError(data)); } OnError(data:any){ console.debug(data.json()); } OnSuccess(data:any){ this.FetchData(); } SuccessGe ...

Order Angular by a derived result

I have a question regarding my app: I am displaying a list of elements, each with different properties. One of these properties is used to retrieve another value from a factory. I would like to be able to sort the list based on this calculated value. Is t ...

Idiosyncratic TypeScript behavior: Extending a class with comparable namespace structure

Lately, I've been working on creating a type library for a JavaScript written library. As I was defining all the namespaces, classes, and interfaces, I encountered an error TS2417 with some of the classes. I double-checked for any issues with method o ...

SSL Offloading and Cross-Origin Resource Sharing

I am currently facing a challenge with my two applications located on separate servers. One acts as the frontend machine while the other serves as the backend API. Our setup involves SSL termination at the load balancer for security. The issue arises when ...

How can I change an icon and switch themes using onClick in react js?

I have successfully implemented an icon click feature to change the colorscheme of my website (in line 21 and changeTheme). However, I also want the icon to toggle between FaRegMoon and FaRegSun when clicked (switching from FaRegMoon to FaRegSun and vice v ...

Is there a way for me to access the user's gender and birthday following their login using their Google account details?

I have successfully implemented a Google sign-in button in my Angular application following the example provided in Display the Sign In With Google button: <div id="g_id_onload" class="mt-3" data-client_id="XXXXXXXXXXXX-XX ...

What could be causing this issue with the ng-bind and ng-show directives not functioning as expected?

Attempting to show data retrieved from Google's Place Service. Oddly enough, the object can be logged to the console within the controller, but the directives in the HTML file remain blank. Since no map is being used, a div element was passed as the n ...

What is the process for performing type checking on a block of TypeScript code stored in memory?

I am currently integrating TypeScript support into my project called Data-Forge Notebook. My goal is to compile, perform type checking, and evaluate snippets of TypeScript code within the application. Compiling the code seems straightforward using the tr ...

Do not include the node_modules directory in the TypeScript compilation process, except for a specific subdirectory that is

To exclude the entire node_modules directory from TypeScript compilation, you can modify the tsconfig.json file like so: { "compilerOptions": { "module": "commonjs", "sourceMap": true, "target": "es6" }, "exclude": [ ...

I aim to decrease the number of decimal places in the code provided below

When working on an HTML page, I encountered a challenge with the decimal numbers displaying more positions than desired - for instance: 13.16 instead of 13.167. Despite my attempts to rectify this using the code snippet below, it is still not functioning ...

Why are optional members utilized in a TypeScript interface?

Currently, I am engaged in an online tutorial on typescript (although it is not in English, I will translate the example): interface Message { email: string; receiver?: string; subject?: string; content: string; } The concept of the ...

What is the best way to change the date format in the GET API response for all objects

Recently started working with Angular, I'm receiving object data from an API call. data= [ { "Id": 4, "IssueDate": "2021-01-25T15:17:00.85", "ExpiryDate": "2021-01-25T15:25:40.263" ...

Unraveling a date field from JSON with AngularJS filtering

Extracting data from JSON file shows /Date(1435837792000+0000)/ How can I format the date to appear as Oct 29, 2010 9:10:23 AM? ...

Reorganize nested JSON arrays

After receiving a Json array from a web service, I encountered a structure where this array contains other arrays. My goal is to transform this multi-level array into a single-level array in order to create an HTML table. For example, consider the followi ...

Angular validation model driven with parameter passing

My current challenge involves email validation, where I am trying to strike a balance between being strict and permissive. To achieve this, I have created a custom validator with a parameter called 'withsuspicious' that allows me to exclude suspi ...

Unable to display array retrieved from successful http get request on the webpage

I've been struggling to output the result from the success function in this specific way, but unfortunately, I haven't had any success. The code works fine when it comes to returning values for UpcomingEvents and displaying them in HTML, but when ...

The 'import type' declaration cannot be parsed by the Babel parser

Whenever I attempt to utilize parser.parse("import type {Element} from 'react-devtools-shared/src/frontend/types';", {sourceType: "unambiguous"}); for parsing the statement, I come across an error stating Unexpected token, exp ...

Dealing with Errors in the World of AngularJS

Hello everyone, I've created a service to retrieve data from my server in the method below: myApp.factory('CommonHttpService', function($http, $q){ var myUrl; return{ query: function(tableName){ //Constructing the URL myUrl ...

Tips for Combining Multiple Custom Filters in AngularJS

Is there a way to use AngularJS to chain multiple filters together? I have 3 dropdown menus that I want to use as filters to refine the data in a table. I created a Plunk to showcase what I'm trying to achieve, you can view it at this link The filter ...

Combining several arrays to find the array of shared elements as the final result

In my JavaScript/TypeScript application built with Angular, I am facing the challenge of merging multiple arrays and extracting the common values that appear in all arrays. For example: arrayOne = [34, 23, 80, 93, 48] arrayTwo = [48, 29, 10, 79, 23] arrayT ...