Storing and accessing a rootScope parameter and its value in Angular JS cache

Is there a way to cache this basic object ($rootScope.config.app_genres) that I set via $http for a specific amount of time?

 $http.get($rootScope.config.app_ws+'get/genres',{},{cache:true}).success(function(response) {
    $rootScope.config.app_genres =  response;
  });

I'm looking to cache it to avoid making the same http request repeatedly.

Answer №1

According to the $http documentation, it is possible to customize your own cache object instance by using the cache configuration option.

In this example, a custom $cacheFactory is created with an overridden put method to automatically clear the cache after a certain timeout period. Please note that this implementation is specific to a single URL. To create a more generic timer cache object, further modifications may be needed.

function Ctrl($scope, $http, $cacheFactory, $timeout) {
  var timedCache = $cacheFactory('myCache'),
      TIMEOUT = 5000,
      cacheTimer = null;

  timedCache._put = timedCache.put;
  timedCache.put = function (key, val) {
    console.log('caching', key);

    $timeout.cancel(cacheTimer);
    cacheTimer = $timeout(function () {
      console.log('clearing cache for', key);
      timedCache.remove(key);
    }, TIMEOUT, false);

    timedCache._put(key, val);
  };

  $scope.request = function () {
    $http.get('/echo/json', {
      cache: timedCache
    })
    .success(function (data) {
      console.log('received', data);
    });
  };
}

To see this in action, check out the working fiddle here: http://jsfiddle.net/sirhc/jvLPX/

Answer №2

Hey there! I'm really hoping that Angular has a built-in feature for this, but it seems like others might have to add it.

One possible solution could be assigning it to a new variable like so:

$rootScope.dataCache = $rootScope.data;

$rootScope.cacheTimer = 50000; 

In your website's application, always make sure to read from $rootScope.dataCache and set up a routine to check and/or automatically update when the cache timer has expired. This way, you can recall the server-side data and reassign it as needed.

Any thoughts on this approach?

Answer №3

This is the method I implement to store templates in cache

$http.get(/*URL*/, {cache: $templateCache})
    .success(function () { ... })
    .error(function () { ... });

However, you may find this alternative approach more suitable for your needs

Answer №4

To meet your caching needs, consider implementing cache busting. For example, if you only want to cache data for a set amount of time (x seconds), you can include a cache busting query parameter with the following value:

Math.floor(new Date().getTime() / (x * 1000))

This will result in the request appearing as follows:

$http.get(url,{cacheBuster: Math.floor(new Date().getTime() / (x * 1000))},{cache:true})

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

Why Isn't the Element Replicating?

I've been working on a simple comment script that allows users to input their name and message, click submit, and have their comment displayed on the page like YouTube. My plan was to use a prebuilt HTML div and clone it for each new comment, adjustin ...

Grouping JavaScript nested properties by keys

I have a specific object structure in my code that I need to work with: { "changeRequest": [{ "acrId": 11, "ccrId": "", "message": "test message" }, ...

Encountered an Uncaught ChunkLoadError with Vercel Next.js: Chunk 0 failed to load

Upon removing the node modules and package-lock.json files, I encountered the error mentioned above when attempting to reload any page. The project works fine after being restarted for the first time. However, upon reloading the page again, it displays a b ...

Issues with NodeJS's "readline" module causing prompts not to be displayed

Recently, I decided to have some fun by creating a 'note' manager using NodeJS. However, I ran into an issue when trying to use readline.question() to prompt the user for their input on managing notes. The prompt was not being displayed as expect ...

Differences in Loading Gif Visualization Across Chrome, Safari, and Firefox

Having an issue with a loading image in Chrome, while it displays correctly in Safari and Firefox. In Chrome, I see two half-loading images instead of one whole image. Struggling to find a solution for this problem, any assistance would be greatly apprecia ...

Utilizing jQuery/Javascript to replicate the data from a table while excluding the header and then pasting it to the

I am attempting to replicate the data from a table while disregarding the header/title row and copying it to the clipboard in the exact same way as manual selection and copy. I came across a post on how to choose Select a complete table with Javascript (t ...

Can a nodeJS script be written to automate selecting options and filling out forms in HTML?

Greetings everyone, I am new here so please excuse me if my formatting is not up to par. Currently, I am tackling a project for an internship and after some extensive research, I am stumped on how to automate certain reports in the next phase. In summary ...

Retrieve the Checked Value of a Checkbox Using Ajax Post in MVC

Can anyone provide assistance? This is the code I am working with: Index.cshtml <!DOCTYPE html> <html> <head> <title>jQuery With Example</title> @Scripts.Render("~/bundles/jquery") <script type="text/javascri ...

Incorporate a fresh element into an object after its initial creation

Hello, I am looking to create an object in JavaScript that includes an array-object field called "Cities." Within each city entry, there should be information such as the city's name, ID, key, and a District array object containing town data for that ...

The event to close the HTTP connection in the Node server always triggers

I want to set up a close event that triggers before the server shuts down. To achieve this, I have implemented the following code: var express = require('express'); var app = express(); var http = require('http').Server(app); var list ...

Exploring the CSS scale transformation alongside the Javascript offsetHeight attribute

After combining offsetHeight with scale transformation, I experienced a strange result. Below is my simple HTML code: <body> <div id="id01"> Some Text </div> <div id="id02" style="transform-origin: left top; transf ...

Can someone provide a description for a field within typedoc documentation?

Here is the code snippet: /** * Description of the class */ export class SomeClass { /** * Description of the field */ message: string; } I have tested it on the TSDoc playground and noticed that there is a summary for the class, but not for it ...

"Looking to trigger a server click using JQuery or Javascript in your code? Here's how you can

I am facing an issue with triggering a Server-Side OnClick event on an ASP Server Button within a User Control using JavaScript or JQuery. The current methods I have tried do not produce the desired result as they do not actually simulate a user clicking t ...

Streamlining the process of implementing click events on elements selected by class using jQuery

Slowly but surely, I am gaining familiarity with jQuery and have reached the point where I desire to abstract my code. However, I am encountering issues when attempting to define click events during page load. Within the provided code snippet, my objectiv ...

What could be causing the visibility issue with my navigation items in the bootstrap navigation bar?

Currently, I am experiencing a puzzling issue with the navigation bar on my live website. The navigation items seem to flicker for a brief moment and then disappear entirely. This unexpected behavior is certainly causing me some concern. I crafted the us ...

Conflicting submissions

Can anyone help me with a JavaScript issue I'm facing? On a "submit" event, my code triggers an AJAX call that runs a Python script. The problem is, if one submit event is already in progress and someone else clicks the submit button, I need the AJAX ...

What is the method for including preset text within a search bar?

My current issue is as follows: When the searchbox is focused, it appears like this: -------------------- -------------------- Upon exiting the searchbox, a string will automatically be added to it: -------------------- Search -------------------- I a ...

Saving the object returned by the useRef hook into the Redux state

I have a question. I am developing a music platform similar to Spotify using Next.js. To manage states, I am utilizing Redux Toolkit. In order to play music, I have integrated the audio element within a component that includes controls to adjust the music ...

Vue not triggering computed property sets

As per the guidelines, I should be able to utilize computed properties as v-model in Vue by defining get/set methods. However, in my scenario, it isn't functioning as expected: export default{ template: ` <form class="add-upload&quo ...

Experience the power of CanJS Observable data objects with the added feature of

When working with canJS Observable, I encountered an issue where I cannot use dots in object keys because canJS interprets them as nesting. For example, if I try to create a new observable like this: var obs = new can.Observe( { "div.test-class": { "color ...