Retrieve all properties associated with the current instance in the Angular 2 controller

I am looking to assign class variables with values from session storage if they exist, otherwise the variable will retain its default value initialized in ngOnInit.

private getTableSessionItems = () => {
    var tSession = JSON.parse(sessionStorage.getItem('tableSession'));

    if(tSession){
        for (var property in tSession) {
            if (tSession.hasOwnProperty(property)) {
                this[property] = tSession[property];
            }
        }
        console.log('tableSession is true');
    }
    else{
        this.setTableSessionItems();
        console.log('nope keep trying', tSession);

    }
}

Answer №1

One way to access and update properties within the current class is by using dynamic methods:

private fetchTableSessionItems = () => {
    var tableSession = JSON.parse(sessionStorage.getItem('tableSession'));

    if(tableSession){
        for (var prop in tableSession) {
            if (tableSession.hasOwnProperty(prop)) {
                this[prop] = tableSession[prop];
            }
        }
        console.log('table session data retrieved successfully');
    }
    else{
        this.setTableSessionItems();
        console.log('unable to retrieve table session data', tableSession);
    }
}

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

Get detailed coverage reports using Istanbul JS, Vue JS, Vue CLI, Cypress end-to-end tests, and Typescript, focusing on specific files for analysis

I have a VueJS app written in Typescript that I am testing with Cypress e2e tests. I wanted to set up coverage reports using Istanbul JS to track how much of my code is covered by the tests. The integration process seemed straightforward based on the docum ...

Encountering Syntax Errors during Angular 6 production build

I encountered an issue with my project. Everything was running smoothly, and even when I executed the command ng build --prod, it compiled successfully and generated the dist folder in my project directory. However, after copying this folder to the htdoc ...

React, Redux, Thunk - the trifecta of powerful

After spending a considerable amount of time struggling with this particular piece of code, I have scoured online resources such as Stack Overflow and the documentation, but there is still something that eludes me... The code in question revolves around t ...

JQuery Ajax encounters a 500 error message due to an internal server issue

I'm currently using the jQuery library to send an ajax request to a PHP file. Initially, everything was working perfectly fine with a relative path like this: url:"fetch_term_grades.php", However, when I modified the path to be more specific like th ...

Error: Unable to assign value to property 'src' because it is null

Currently, I am attempting to display a .docx file preview using react-file-viewer <FileViewer fileType={'docx'} filePath={this.state.file} //the path of the url data is stored in this.state.file id="output-frame-id" ...

Tips for ensuring a custom menu closes when clicking outside of it instead of on the menu itself

Building off a recent inquiry, I am aiming to have my menu close whenever I click outside of it. At the moment, clicking the "Hamburger Menu Button" opens and closes the menu. It will also close when I click a link on the menu or the menu itself. However, ...

Is it possible for an ul to be displayed beneath a white section within an li

I am working on a JQuery carousel that is displaying correctly, but I want to make a small adjustment to the content: <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-1 jcarousel-item-1-horizontal" style="float: left; list-style: none ...

Incorporate v-if to target a particular item within a v-for loop

On my Vue page, I have the following HTML code snippet: <div v-for="profile in lab.profiles" v-if="edit || profile.active" class="lab-tests-row-div" @mouseover=""> <div class="clickBox" :class="['clickBox-' + lab.id + ' ...

Which task runner should I use for my NodeJS application - Gulp or Grunt?

Imagine I have Stylus with nib, Jade, Passport, Mongoose, along with other modules that I integrate into my NodeJS application. Given that all pre-compilers are functioning well as Node modules, is it necessary to use gulp or Grunt to streamline the proce ...

Ways to retrieve information from a intricate JSON structure?

Can anyone help me understand why I am unable to access the data in the detail option of the JSON? My goal is to load the firstName, lastName, and age into a list for each object. var data = { "events": [{ "date": "one", "event": "", "info ...

Tips for utilizing the getServerSideProps function

I want to improve the SEO friendliness of my page by utilizing the getServerSideProps method. Despite searching online, I couldn't find a specific example that fits my situation. I am uncertain about how to proceed since I currently have a useEffect m ...

How can I extract the return value of a JSON object and store it in a variable?

I am attempting to develop a dynamic chart by utilizing data retrieved from a function housed inside a JSON object. The JSON object is fetched through the Relayr Javascript API, and looks like this: relayr.devices().getDeviceData({ token: tok ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...

Loading identical items using jQuery Ajax

I have a situation where an ajax request is returning multiple URLs which I am using to create images like: <img URL="1" /> <img URL="1" /> <img URL="2" /> <img URL="1" /> <img URL="3" /> <img URL="2" /> and so on... ...

Steps to displaying a genuine Docx file within a Material CardMedia

Currently, I am facing an issue with positioning a docx file in my app. Interestingly, jpg and mp4 files are displaying correctly, but the docx file is not positioned as expected. If you want to try it out, simply open a doxc file. In the FileContentRend ...

The error message "Property 'originalUrl' is not found in type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'" appeared

In my TypeScript project, I am utilizing a gulpfile to initiate the process. Within the gulpfile, I am using express where I encounter an issue while trying to access req.originalUrl, with req being the request object. An error is thrown stating Property ...

Attempting to gather data from an HTML form and perform calculations on it using JavaScript

Looking for help with extracting user input from HTML and performing mathematical operations in JavaScript. Coming from a Python background, the variable system in JavaScript is confusing to me. Can someone provide guidance on how to achieve this? <div ...

Choosing options from an API response in a REACT-JS application

I have a Select Component in my application and I want it to automatically show the selected data once the response is received. import Select from "react-select"; <Select menuPlacement="auto" menuPosition="fixed" ...

What is the best way to pass a conditional true or false value to React boolean props using TypeScript?

I am currently utilizing the Material UI library in combination with React and Typescript. Whenever I attempt to pass a conditional boolean as the "button" prop of the component, I encounter a typescript error stating: Type 'boolean' is not assi ...

What is the best way to tally a score after analyzing two spans in Javascript?

I have 3 spans where 2 contain an alphabet each. The third span is left blank for the result of comparing the first 2 spans. I need to display the result in the last span, showing a value of 1 if the two spans contain the same alphabet. Can anyone sugges ...