When browser refreshes on an Angular UI-Router page and shows null values, how can the data be preserved?

Using Angular Js Ui router, I am able to call a function and retrieve data from the Db successfully after clicking a button.

However, when the browser is refreshed, the data becomes null and triggers a 500 error response.

The issue seems to be related to the state configuration path and the null values in the controller. Is there a way to persist the data in the ui-state provider?

Example Url:
http://localhost/Myproject/#/home/Retailer/retailerId=1?retailerCode=3

On button click, the values are passed as parameters:
 $state.go('Home.retailer', { 'retailerId': $scope.param1, 'retailercode': $scope.param1});

Upon page refresh, the values become null in the module.

.state('home.retailer', {

        url: '/contract/:retailerId:9?retailercode:1',
        params:{
                   'retailerId': '9', 'retailercode': '1' 
       },
        views: {
            '@': {
                templateUrl: baseUrl + 'retailr/retailerList',
                controller: 'home',
            }
        },
        data: {
           Name: '',
            Img: 'Images/1.png'
        }

    })

Note: On button click, the service should return the data.

Issue: Upon page refresh, the module checks home.retailer and reverts to the service. How can the data be persisted when refreshing the browser?

Specifying the parameters is crucial: params:{ 'retailerId': '9', 'retailercode': '1' },

Due to the null response, the retailer id and code are passed to the service inside the controller. 
 `RetailerService.pageLoad($scope.retailerId,$scope.retailercode)` when the button is clicked ,
RetailerService.pageLoad($scope.retailerId :9 ,$scope.retailercode :1) , 

Upon page refresh: RetailerService.pageLoad($scope.retailerId : null,$scope.retailercode : null)` 

Answer №1

In order to maintain data on refresh, it is important to store it in the browser's storage. A great example of this is a factory utilizing localStorage.

app.factory("storageFactory", function($window) {
  return {
    setData: function(value) {
      $window.localStorage && $window.localStorage.setItem('my-storage', value);
      return this;
    },
    getData: function() {
      return $window.localStorage && $window.localStorage.getItem('my-storage');
    }
  };
});

It is advisable to set data at different points in your controller, and then retrieve the data on page load to ensure any previously set variables are retrieved.

Additionally, instead of localStorage, sessionStorage is an alternative option as mentioned below. The choice between the two should be based on your specific requirements.

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

Is it possible for JavaScript to identify modifications in the HTML, like an input made with Ctrl+Shift+I?

Check out this website I'm currently working on. As a fun challenge for users, we're encouraging them to use ctrl+shift+i to manipulate the HTML and modify certain elements. Is it possible for Javascript or CSS/HTML to detect these changes? For ...

Concealing certain columns when the table exceeds a certain size

Hello everyone, I am just starting out in the world of React and web applications. Please feel free to reach out if anything is unclear to you. Here is the table structure that I currently have: <div> <table id="mytableid" className=&qu ...

Utilizing Ajax for Efficiently Updating a Singular Field within a Designated Object

How can I use Ajax to Update a Single Field in a Specific Object? I have a table in my postgres database with numerous records. I am interested in using a jquery Ajax request to update just one field in a particular object within that table. Is it possibl ...

Different techniques to access values in a JSON array without relying on specific index positions

After making a request to an API, I received a JSON array with various attributes. One of the attributes is "State" and my task is to extract all the "EventName"(s) where State: "PR". The user will select the state from a dropdown menu. In order to achiev ...

What is the best way to save a multi-line text file - should it be stored as a regular text file or as a

I am currently developing a discord bot with discord.js and NodeJS. One of the challenges I am facing is sending a multi-line message (approximately 20 lines) to a specific channel for a particular command. In order to enhance the code's readability, ...

Ways to verify if a component triggers an event in VueJS

I am currently working with two components within my application. The Child component emits an 'input' event whenever its value is changed, and the Parent component utilizes v-model to receive this updated value. In order to ensure that the funct ...

Tips for managing variables to display or hide in various components using Angular

In this example, there are 3 main components: The first component is A.component.ts: This is the parent component where an HTTP call is made to retrieve a response. const res = this.http.post("https://api.com/abcde", { test: true, }); res.subscribe((r ...

"Encountering an issue with AJAX file upload displaying an error message for

Before I showcase my code, allow me to explain my objective. My goal is to create a page that updates a user's details in the database using AJAX. Initially, I successfully achieved this task. Subsequently, I wanted to enhance the functionality by inc ...

Issue with Angular Routing When Deployed

After developing a website utilizing Angular 6 and hosting it on GitHub, I incorporated Routing to automatically direct users to the '/home' page instead of the main '/' page. You can access the project by clicking on this project link. ...

Exploring the TypeScript compiler API to read and make updates to objects is an interesting

I'm delving into the world of the typescript compiler API and it seems like there's something I am overlooking. I am trying to find a way to update a specific object in a .ts file using the compiler API. Current file - some-constant.ts export co ...

Is it preferred to utilize v-show in combination with v-for?

I understand that using "v-if" with "v-for" is discouraged, but I'm unsure about the case of "v-show" since it simply toggles the display attribute. Here is the code for reference. Essentially, I am trying to switch between 3 different types of fi ...

Is it possible to view JavaScript methods in the watch window of IE's debugger?

Can I view custom methods in the IE developer toolbar's watch window? For example, if I have a global function named hello, can I locate it within the DOM? function hello() { alert("hello"); } If so, where in the watch window would I find them? ...

What is causing the duplication of leaves when using this DFS implementation?

I created an algorithm to compare if two trees have the same leaves. https://i.sstatic.net/lpO2C.png Both trees display matching leaf numbers in the exact order, resulting in a true outcome. Below is the code that I formulated: function leafSimilar(root ...

JsDoc presents the complete code instead of the commented block

I have a VUE.JS application that needs to be documented. For .VUE components, we are using Vuese. However, when it comes to regular JS files like modules, we decided to use JsDoc. I have installed JsDoc and everything seems fine, but when I generate the HT ...

combining input fields for editing as a single unit instead of individually

Current Situation : At the moment, I have a form where individual records of input fields such as firstName, lastName, and email can be edited and saved without any errors. Requirement : However, I now want to be able to edit and save the firstName and ...

Angular 2: Issue with Component not reinitializing when query parameters change

I am currently working with Angular 2 and the latest router component to create a search functionality. Upon clicking the search button for the first time, the router navigates to the search component and retrieves data from the service. However, I have no ...

Sending back various results in a javascript function

I am attempting to correlate test scores with values from the level array in order to extract selected values into an output array. However, when I execute the following script in the Firebug console, I encounter the error message "TypeError: level is unde ...

Trouble with React Material Modal TransitionProps triggering onEntering event

Currently, I am in the process of updating Material UI to version 5. Initially, I encountered an error stating that onEntering is deprecated and should be replaced with transitionprops. There is a specific method (let's name it doSomething) that I wa ...

React - The issue with my form lies in submitting blank data due to the declaration of variables 'e' and 'data' which are ultimately left unused

Currently, I'm working on incorporating a form using the react-hook-form library. Despite following the documentation and utilizing the handleSubmit function along with a custom Axios post for the onSubmit parameter like this: onSubmit={handleSubmit( ...

JavaScript program that continuously reads and retrieves the most recent data from a dynamically updating JSON file at regular intervals of every few seconds

I am a beginner in JavaScript and I'm facing an issue with displaying the most recent values from a .json file on an HTML page. The file is updated every 10 seconds, and I am also reading it every 10 seconds, but I'm not getting the latest data. ...