Angular service returning a promise for retrieving data from local storage

My application's configuration data is stored on an API server (specifically, form.io) and since it will rarely be changed, I have decided to store it in localStorage. To achieve this, I check for the data in localStorage within my getStationConfig service. If the data is not found locally, I fetch it from the API and save it locally for future use.

The challenge lies in returning the data from localStorage as a promise so that it can be handled by my controller code which is expecting a promise. The snippet of code used to retrieve the data in the controller looks like this:

var stationPromise = shiftService.getStationConfig().then(function(data) {
  vm.configSlots = data;
});

Here is how my service is structured:

var getStationConfig = function() {
  // Check if information is stored locally.
  var config = JSON.parse(localStorage.getItem('cfdConfig'));
  if (config) {
    return config;
  }

  // Retrieve configuration info from the appropriate Config resource submission.
  // Code adapted from ngFormioHelper.FormioAuth.
  var token = localStorage.getItem('formioToken');
  var config = {
    disableJWT: true,
    headers: {
      "x-jwt-token": token
    }
  };
  return $http.get(Formio.getAppUrl() + '/config/submission', config)
    .then(function(result) {
      // Format the data before returning it to the controller

      // Store the formatted info in localStorage to reduce calls to the API
      localStorage.setItem('cfdConfig', JSON.stringify(allSlots));

      return allSlots;
    },
    function(err) {
      console.log(err);
    });
};

While the data returned from localStorage is in the same format as 'allSlots' at the end, it is not wrapped in a promise causing issues with the controller. I am seeking advice on how to wrap or return it as a promise. Should I try calling localStorage via $http.get() or explore another approach?

Thank you.

Answer №1

Integrate the $q promise service into your own service and employ it to deliver the data enveloped in a promise

if (config) {
  return $q.resolve(config);
}

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

Using jQuery to add an element at the current caret position

Within my contentEditable div, there is a table nested. Here is an example of the HTML structure: <div id="divId" contenteditable="true"> <table> <tbody> <tr> <td><br></td> ...

What caused Jasmine to consistently anticipate a true result in Protractor for Web UI automation testing?

I am currently working on automating Web UI testing for an angular 2 website. However, I have encountered a problem while trying to verify the success of the login step. Even when entering the wrong password or using the incorrect XPath for the logout butt ...

Tips on minimizing object array and extracting its worth using javascript

I am currently facing a challenge with reducing an object array. The array is as follows: arr=[{title: 'AP', CurrentDate: 2019-07-31, Status: 'done', NoOfEvents:'6' }] My goal is to reduce this array object specifically to ex ...

The implementation of a conditional anchor tag with an on-click function

Suppose we have a list of objects with names and link IDs. If the link ID is null, only display the name. If there is a value for the link ID, wrap the name in an anchor tag and bind it to a click event. For example, Object A is: objectA { name: "Obje ...

What is the correct placement for $.validator.setDefaults({ onkeyup: false }) in order to deactivate MVC3 onKeyup for the Remote attribute?

After coming across various solutions on how to disable the onKeyup feature of MVC3 Remote Validator, I noticed that many suggest using the following code: $.validator.setDefaults({ onkeyup: false }); However, I'm in a dilemma about where to place t ...

I possess a webpage containing a div element that is loaded dynamically through ajax

One issue I'm facing is with a page containing a div that gets loaded via ajax when a button is clicked. The problem arises when a user tries to refresh the page by pressing F5, as the content of the div gets lost! Is there a way to ensure that when ...

AngularJS loads the index into the ui-view using UI-router

While working on a site using AngularJS, everything appears to be working perfectly when run locally. However, in the deployed version, there is a strange issue where 'index.html' is being loaded in the ui-view instead of the specified partial at ...

Identifying the moment when the body scroll reaches the top or bottom of an element

I have been experimenting with javascript and jquery to determine when the window scroll reaches the top of a specific element. Although I have been trying different methods, I have yet to see any successful outcomes: fiddle: https://jsfiddle.net/jzhang17 ...

Transform the checkbox selection into an active hyperlink upon being selected

Currently, I am in the process of designing a form that allows visitors to select items they would like to view by checking relevant checkboxes. Upon clicking a Request button, the URLs of the selected items are displayed. I aim to have the URL appear as ...

Vue.js: Incorporating Multiple CSS Templates in a Single Application

As a beginner in Vuejs, I am trying to figure out how to incorporate multiple templates into one application. For example, I want to use the Flatkit template for my SignIn page and a different template (Dashboard) for the Admin dashboard. How can I integra ...

Angular's end-to-end testing capabilities for backend systems

Is it possible to utilize Angular's e2e framework for testing web services and conducting database validations, essentially for backend testing, or is its primary function limited to front end UI testing? ...

What is the process for linking a click event to an already established function in AngularJS?

Having an issue with my code. $('#formSubmit').click(function() { alert("Hi"); // a bunch of long code }; The functionality works well when clicking the formSubmit button. However, I now want to create a separate function and bind it to the for ...

Thinking about how to incorporate the value of a JavaScript variable into a CSS variable?

I am attempting to utilize Window.innerWidth and load the resulting value into a CSS variable, but it doesn't appear to be functioning correctly. What could I be doing incorrectly? function myFunction() { var w = window.innerWidth; document. ...

Node.js Request Encoding Using Google Translate

I have developed a node.js module to use the Google Translate API. module.exports = function(sourceText, sourceLang, targetLang, callback) { var qst = qs.stringify({ client: 'gtx', sl: sourceLang, tl: targetLang, ...

retrieving specific values from a row in an HTML table and converting them into a JSON array

function extractRowData(rowId) { const row = [...document.querySelectorAll("#stockinboundedittable tr")].find(tr => tr.id === rowId); const rowData = Object.fromEntries( [...row.querySelectorAll("input")].slice(1).map(inp => [inp.id.replace(/ ...

Using an image tag with dual quotes in Vue.js

I am currently working on a feature where users can upload an image and then have it displayed after the upload is complete. However, I am facing an issue where the response link of the image contains a double quote, and when I use the <img> tag to ...

Unable to transfer array elements to a function within PhantomJS

I am facing a challenge in extracting the source code from multiple webpages simultaneously. The links are stored in an array from a source text file. While I am able to successfully loop through the array and display the links, I encounter an issue when p ...

Please replicate an element based on user input using Javascript

When I click on the ADD button, the text appears below but in the same column. There are 2 input fields. I have used: <input id="accordion_input" type="text"/> Another one is: <div id="accordion_body" class="panel-body"></div&g ...

The placement of an object on a webpage

Seeking the (x,y) coordinates of an element using JavaScript, utilizing the offset property from jQuery. Here is my code snippet: var offsets = $('#11a').offset(); var top = offsets.top; var left = offsets.left; console.log("Coor ...

Formatting Google Calendar event lists with jQuery techniques

After spending all day trying to solve the problem of displaying a Google calendar in list format on my website, I finally found some code that works. However, there are still some formatting issues that I can't figure out. I'm not very familiar ...