Is there a way to access and view all cache in Http using AngularJS?

There is a method that I know how to use

var cache = $cacheFactory.get('$http');
cache.get('http://example.com/api/users.json');

I am curious about what other information the data cache contains.

I attempted

console.log(cache) but it only displays function names, not the actual cached data.

I also visited this website

https://docs.angularjs.org/api/ng/service/$cacheFactory

In the provided example, they utilize keys to retrieve data

<div ng-repeat="key in keys">
    <span ng-bind="key"></span>
    <span>: </span>
    <b ng-bind="cache.get(key)"></b>
  </div>

however, I would like to access those specific keys stored in the cache. Something along the lines of:

cache.getKeys()

Answer №1

Upon examining the internal workings of $cacheFactoryProvider, it becomes evident that the data variable remains inaccessible in its original form.

Therefore, the primary method to access this data involves altering the Angular JS source code or enhancing the provider through decoration.


I have made an attempt at implementing this modification, and while it does "work™", I must emphasize that it is merely a Proof of Concept. It could potentially be extended further or integrated into a fork of Angular (even better, submit a PR) to undergo testing with their specification suite to identify any potential issues.

Below are the documented steps outlining my approach:

app.config(function ($provide) {

  // Store the original return value of $cacheFactory(cacheId, options).
  var originalCacheFactory;

  $provide.decorator('$cacheFactory', function ($delegate) {
    
    // Initialize caches holder.
    var caches = {};

    // Prevent overwriting the original implementation.
    if (!originalCacheFactory) {
      originalCacheFactory = $delegate.apply(null, arguments);
    }

    // Define a new cacheFactory method.
    function cacheFactory (cacheId, options) {
      var data = {};

      return caches[cacheId] = angular.extend($delegate.apply(null, arguments), {
        put: function (k, v) {
          // Store values in our local 'data' variable accessible via getAll.
          if (!data[cacheId]) {
            data[cacheId] = {};
          }

          data[cacheId][k] = v;
          
          // Invoke the original .put method.
          originalCacheFactory.put.apply(null, arguments);
        },
        getAll: function () {
          return data[cacheId];
        }
      });
    }

    // Re-implement the $cacheFactory.get(id).
    cacheFactory.get = function (id) {
      return caches[id];
    };

    // Re-implement the $cacheFactory.info().
    cacheFactory.info = function () {
      var info = {};
      forEach(caches, function(cache, cacheId) {
        info[cacheId] = cache.info();
      });
      return info;
    };

    // Return the updated cacheFactory function.
    return cacheFactory;
  });
});

//////////////////////////////////////////////////////////////////

// Log the contents of the $templateCache.
app.run(function ($templateCache, $cacheProvider, $timeout) {
  $timeout(function () {
    console.log($templateCache.getAll());
  });

  // Or
  $timeout(function () {
    console.log($cacheProvider.get('templates').getAll());
  });
});  

Check out this jsBin showcasing the final outcome. Open the console to view the output displaying three stored templates in the $templateCache.


In conclusion:

Answer №2

In my quest to compile a comprehensive list of previous URLs associated with something, I found myself delving into the depths of Angular itself. By gaining access to the Angular module you are incorporating, you can enhance its capabilities to suit your needs. Begin by locating the $CacheFactoryProvider function and identify where it assigns the cache - typically seen as return caches[cacheId] = {. Introduce a new parameter named 'data' within this object before the 'put' method, assigning it the value of 'data' like so: data: data,. Currently, Angular only retains this information locally. This modification allows you to retrieve all stored cache data in an organized manner using objects, with the keys representing the URLs.

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

Getting the most out of Nexmo with multiple websocket connections

I have integrated the code provided by Nexmo (shown below) into my server. However, I am facing an issue where if two callers ping my server, the binary data from the second caller also streams into the same websocket endpoint, resulting in two binary st ...

Dimensions of Bootstrap carousel

I am attempting to create a Bootstrap carousel with full-width images (width: 100%) and a fixed height. However, when I set the width to 100%, the height automatically takes on the same value. I am unsure if the issue lies within my files. <div id="m ...

How many intricate objects are instantiated in memory when running the code snippet provided above?

When looking at the given code, how many complex objects can we identify in memory? function Foo() { this.one = function() { return "one"; } } var f = new Foo(); Foo.two = function() { return "two"; }; Here's what I see: The Foo co ...

When NextJS calls a dynamic page in production, it redirects to the root page

My Desired Outcome When a user inputs https://www.example.com/test, I want them to receive the content of the NextJS dynamic route /test/index.js. This functionality is successful in my local environment. The Current Issue Despite a user entering https:/ ...

Navigate to Element ID with Nuxt.js on click

Currently, I am in the process of developing a Nuxt application and facing a challenge. I want the page to automatically scroll down to a specific element after clicking on a button. Interestingly, the button and the desired element are located within diff ...

Exploring the power of Mongoose with GraphQL queries

Below is a mongoose Schema I have created: name : String, class : String, skills : [{ skill_name : String }] I want to convert this Schema into GraphQL inputs so that I can save them to MongoDB. Can someone help me with this? Something like: input Stud ...

Is there a problem with addEventListener returning false?

What does keeping the third parameter as false in the line below signify? var el = document.getElementById("outside"); el.addEventListener("click", modifyText, false); ...

When using firebase.firestore(), the data displayed is completely different and does not match the content of my actual database documents

I am trying to fetch data from firebase firestore using the following code: let db = firebase.firestore(); let locations = db.collection("location"); console.log("locations", locations); However, the logged data is coming back strange and not showing the ...

JavaScript-powered horizontal sliderFeel free to use this unique text

I'm new to JS and trying to create a horizontal slider. Here's the current JS code I have: var slideIndex = 0; slider(); function slider() { var i; var x = document.getElementsByClassName("part"); for (i = 0; i < x.length; i++) { x[i].styl ...

Why isn't the unit test passing when it clearly should be?

I am encountering an issue with testing a simple function that I have created. Despite the fact that the function works correctly in practice, it is not being tested properly... Explanation of how my function operates (While it functions as intended, the ...

Struggling with incorporating elements into a dynamic CSS3 banner design?

Struggling to add up to 10 text items to the CSS3 animated banner. Having difficulty getting the items to display properly. I'm curious if there is a simpler way to achieve this with animations as shown in this example: http://jsfiddle.net/zp6B8/1/ & ...

Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this iss ...

It is not possible to display JSON data that has been injected using a service within the amchart directive's datapro

I have incorporated amcharts into my custom directive. Now, I need to retrieve the dataProvider for this AmChart from the output of the $http.get service using web services. Despite my efforts, I am encountering difficulties in dynamically assigning the r ...

Is it normal for e.target.result to only work after two or three tries?

Attempting to resize an image on the client side before sending it to the server has been challenging for me. Sometimes, the image does not align correctly with the canvas used for resizing. I have noticed that I need to send the resized image at least tw ...

AngularJS Input field fails to update due to a setTimeout function within the controller

I am currently working on a project that involves AngularJS. I need to show a live clock in a read-only input field, which is two-way bound with data-ng-model. To create this running clock effect, I am using a JavaScript scheduler with setTimeout to trigge ...

Using Three.js to showcase 3 different slices of heatmaps within a 3D environment

I'm working on using Three.js to create a 3D representation of a matrix. Each 2D plane in the matrix should be displayed as a 2D heatmap. Here is an example of what I'm aiming for: https://i.sstatic.net/Kj5yb.png My current obstacle is figuring ...

Utilizing an NPM Mirror: A Comprehensive Guide

Oh no, the npm registry is experiencing issues once more, causing havoc with executing npm install. Query: What is the alternative method for using npm to fetch packages from npm mirrors? Can you suggest any reliable npm mirrors? ...

Prevent onClick event in jQuery and extract parameters from a function call

We've been tasked with implementing a temporary solution to some code, so it might seem a bit silly at first. But please bear with us. The goal is to block the onclick method of an anchor tag, extract the parameters from the function call, and then u ...

Transform the snake code by incorporating a visual image as the face of the serpent

Can someone help me change the snake's face to an image instead of a color fill in this code? And how can I add arrows for mobile compatibility? (function() { // Insert JS code here })(); // Insert CSS code here This code snippet includes functi ...

Attempting to navigate through nested data within existing mapped data

The data set 1 consists of an array that contains another array called data set 2. Currently, data set 1 is being mapped to display a single-column table with data1.name inside it. The data1.name serves as a clickable button that reveals the related data i ...