Getting the value of a variable from a different function within the same class in Angular

Looking for advice on how to refactor my logic to access the namesSplit variable in the evaluateResult function within my executable variable node class. Any suggestions?

export class ExecutableVariableNode implements IExecutableNode {
execute(treeNode: ExpressionTreeNode, exprData: ExpressionData): any {
    let namesSplit = treeNode.name.split('.');
    let key = namesSplit[0];
    let contextEntry = exprData.contextEntry.find(_x => _x.name === key);

    if (namesSplit.length > 1) {
        this.evaluateResult(contextEntry.value);
    }
}

isPrimitive(test): boolean {
    return typeof test !== 'object';
}


// Get Values
evaluateResult(val) {
    if (this.getType(val) === ExpressionVariableType.OBJECT) {
        return Object.values(val);
    }
    else if (this.getType(val) === ExpressionVariableType.ARRAY_OF_OBJECTS) {
        for (let obs of val) {
            for (let n = 0; n < namesSplit.length; n++) {
                if (namesSplit[n] == Object.keys(obs)) {
                    let result = Object.values(obs);
                    console.log(result);
                    break;
                }
            }
        }
    }
    else if (this.getType(val) === LapsExpressionVariableType.ARRAY_OF_PRIMITIVES) {
        throw new StdException('Array of Primitives not allowed!');
    }
    else if (this.getType(val) === LapsExpressionVariableType.PRIMITIVE) {
        throw new StdException('Primtive values not allowed!');
    }
}

}

Answer №1

To make a variable global, define it outside of any function so that it can be accessed throughout the class.

export class ExecutableVariableNode implements IExecutableNode {

    namesSplit: any;

    execute(treeNode: ExpressionTreeNode, exprData: ExpressionData): any {
        this.namesSplit = treeNode.name.split('.');
        let key = this.namesSplit[0];
        let contextEntry = exprData.contextEntry.find(_x => _x.name === key);

        if (this.namesSplit.length > 1) {
            // Call the evaluateResult() method here
            this.evaluateResult(contextEntry.value);
        }
    }

    isPrimitive(test): boolean {
        return typeof test !== 'object';
    }


    // Get Values
    evaluateResult(val) {
        if (this.getType(val) === ExpressionVariableType.OBJECT) {
            return Object.values(val);
        }
        else if (this.getType(val) === ExpressionVariableType.ARRAY_OF_OBJECTS) {
            for (let obs of val) {
                for (let n = 0; n < this.namesSplit.length; n++) {
                    if (this.namesSplit[n] == Object.keys(obs)) {
                        let result = Object.values(obs);
                        console.log(result);
                        break;
                    }
                }
            }
        }
        else if (this.getType(val) === LapsExpressionVariableType.ARRAY_OF_PRIMITIVES) {
            throw new StdException('Array of Primitives not allowed!');
        }
        else if (this.getType(val) === LapsExpressionVariableType.PRIMITIVE) {
            throw new StdException('Primtive values not allowed!');
        }
    }
}

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

Currently, I am working on developing a Discord bot using discord.js within Visual Studio Code. So far, all of the commands that I have implemented are functioning properly except for one. This specific command is a

Currently, I am immersed in the development of a comprehensive AIO Discord Bot similar to popular ones like "Dyno Bot" or "Carl Bot." The initial phase involved creating basic commands such as ping, avatar, and so on. Now, I have ventured into crafting a ...

Save serializable information in either a char or string variable within Java programming

Object obj = randomForest.getClassificationByMaxProb(attributes); System.out.println("Assigned class: " + obj); The output shows: Assigned class: 1 I need to save the value 1 in either a char or an int variable. ...

The back button in Angular that activates the previous route

I am encountering an issue with my Angular 14 application. Upon loading, a modal popup is displayed at the route: http://localhost:4200/select-role this.router.navigateByUrl(AppConstants.SCREEN_ROUTES.HOME).then(success => this.loaderService.hide()).ca ...

Querying MongoDB using aggregation to find documents with a specific date range difference

I have been working on setting up a cron job to synchronize my documents. The goal is for the job to attempt syncing a specified number of times, but only after waiting at least 2 hours since the last attempt. Each document has a "lastSyncAt" field that I ...

Include a link in the email body without displaying the URL

My concern revolves around displaying a shortened text instead of the full link within an email. When the recipient clicks on "Open Link," they should be redirected to the URL specified. The text "Open Link" must appear in bold. My current development fram ...

Restrict the PHP generated Json response to display only the top 5 results

I need to modify my search bar so that it only displays the top 5 related products after a search. public function getProducts() { if (request()->ajax()) { $search_term = request()->input('term', ''); $locatio ...

Obtaining fresh data during an ajax update

I've noticed that my code is functioning correctly, but I'm having trouble grasping it completely. Could someone please provide an explanation? Here is the code snippet: <script type="text/javascript"> var portletNamespace = '#& ...

Jquery: Undefined Key/Value Declaration

I'm diving into the world of associative arrays for the first time and trying to access data using keys. While my array is being constructed successfully, I'm struggling to actually retrieve the data. As a result, the console.log statement at the ...

Tips for displaying filtered items on the MongoDB terminal

I have objects categorized by cost and date of addition, each user having such categories. My goal is to display all categories for the month "08" in the console. How can I achieve this? Currently, my code retrieves the entire object with the user informat ...

Using Jquery to reset the form I have filled out

I am facing an issue with my forms. I have 2 form input fields and 1 select form. When I select option A from the select form, one of the input fields should hide and automatically reset/clear. I have successfully implemented the hide logic, but unable to ...

When attempting to decrypt with a password using CryptoJS, AES decryption returns an empty result

Example The code snippet below is what I am currently using: <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script> <div id="decrypted">Please wait...</div> Insert new note:<input type="te ...

How should one properly import and compile external HTML within an Angular controller?

I'm on the search for an answer to a question that seems to have eluded me so far. I am working with Angular 1.5.7 and I am trying to import external HTML into my project, specifically into a component controller for use in a tooltip, but I am struggl ...

Unlocking nested JSON data in React applications

Encountering an issue while retrieving a nested JSON object from a local API endpoint /user/{id}. Here is an example of the JSON object: {"userId":122,"name":"kissa","email":"<a href="/cdn-cgi/l/email-protect ...

Unable to get PrependTo to remove itself when clicked

Below is a custom jQuery script I put together: $(function(){ $("a img").click(function() { $("<div id=\"overlay\"></div>").hide().prependTo("body").fadeIn(100); $("body").css({ ...

What is the process for exporting Three.js files to .stl format for use in 3D printing?

I stumbled upon a page with this link: Is it possible to convert Three.js to .stl for 3D printing? var exporter = new THREE.STLExporter(); var str = exporter.parse(scene); console.log(str); However, despite using the code provided, I am unable to export ...

Dealing with CORS and multiple headers

After setting up CORS for my web api project and deploying it to local IIS, I encountered an issue when trying to call a controller method from Angular. The error message displayed was as follows: SEC7128: Multiple Access-Control-Allow-Origin headers ar ...

How can we efficiently validate specific fields within arrays and objects in express-validator by utilizing the body() method?

I have organized my field names in an array as follows: const baseFields = [ 'employeeNumber', 'firstName', 'lastName', 'trEmail', 'position' ]; These are the only input fields I need to focus on for valid ...

Is there a way to condense my child table directly below its parent column?

When attempting to collapse the "child tr" within the "tr" in my code, the collapse is not positioning correctly underneath its parent tr. While it works fine in a JSFiddle, the issue arises when using my editor and live preview. In this scenario, both "ch ...

Transmit information via AJAX using the React Flux design pattern

Here is my React code snippet: var AddRecord = React.createClass({ getInitialState: function() { return { Data: [] } }, sendData : ...

Bug allows unauthorized access to password in Bootstrap Password Revealer

Whenever I try to reveal a Bootstrap password using the eye button, my PC freezes. Strangely, an input is automatically added even though there are no codes for it. This auto-increasing input causes my browser to hang and eventually crashes my entire PC. C ...