Optimizing AngularJS performance with REST service caching

My AngularJS application requires caching of REST service responses, and I've come across libraries like angular-cached-resource that store data in the local browser storage.

However, there are times when certain cached responses need to be deleted due to POST / PUT / DELETE REST calls. In such cases, it's necessary to clear the cache so that the call is sent to the server again.

If the server sends values like 'expires' or 'etag' in the HTTP Header, do I have to manually read the header and react accordingly? Or does AngularJS offer a library that can handle this automatically?

Determining whether to hit the server instead of reading from the cache depends on the HTTP Header Cache fields and certain calls requiring a response indicating the need for a reload (e.g., "reload of every user settings element"). This mandates creating a map that specifies which REST services should contact the server next time they are executed or if the Cache expires based on the HTTP Headers.

Are there any AngularJS libraries that facilitate this process, or do you have alternative recommendations? Does this scenario remind you of the Observer or PubSub pattern?

Additionally, Is there a way to implement PubSub functionality without utilizing cache/local storage (and hence no HTTP Header Cache controls)? I want to avoid hitting the server unless absolutely necessary (e.g., upon receiving an event like "reload of every user settings element" from a previous REST call).

Answer №1

Here is a sample implementation you can experiment with.

app.factory('requestService', ['$http', function ($http) {

    var data = {};

    var service = {
        getCall : funtion(requestUrl, successCallback, failureCallback, getFromCache){
                    if(!getFromCache){
                        $http.get(requestUrl)
                            .success(function(response){
                                successCallback(response);
                                data.requestUrl = response;
                            })
                            .error(function(){
                                failureCallback(data);
                            })
                    }else{
                        successCallback(data.requestUrl);
                    }
                },
        postCall : function(requestUrl, paramToPass, successCallback, failureCallback, getFromCache){
                    if(!getFromCache){
                        $http.post(requestUrl, paramToPass)
                             .success(function(response){
                                successCallback(response);
                                data.requestUrl = response;
                             })
                             .error(function(response){
                                failureCallback(response);
                             })
                    }else{
                        successCallback(data.requestUrl);
                    }
        }
    };

    return service;
}]);

This code snippet is a basic example I designed to help you understand the concept. Feel free to try it out and make adjustments as needed.

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

Ways to display all current users on a single page within an application

I have come across a project requirement where I need to display the number of active users on each page. I am considering various approaches but unsure of the best practice in these scenarios. Here are a few options I am considering: 1. Using SignalR 2. ...

When attempting to check and uncheck checkboxes with a specific class, the process fails after the first uncheck

I have a set of checkboxes and one is designated as "all." When this box is clicked, I want to automatically select all the other checkboxes in the same group. If the "all" box is clicked again, I would like to deselect all the other checkboxes. Currently ...

Exploring CryptoJS in a Vue.js project

https://github.com/brix/crypto-js I successfully installed CryptoJS using npm i crypto-js. However, I am facing difficulty in integrating it into my project. When I attempt to use the following code: // Decrypt var bytes = CryptoJS.AES.decrypt(cipher ...

JSP form continues to submit despite JavaScript validation returning false

On my JSP page, I have a form named "deleteCont" and a JavaScript function called "validateDelete". When the user clicks the "Delete contact" button, the "validateDelete" function is triggered successfully, showing an alert message. Unfortunately, even whe ...

How can JavaScript be integrated with Django static URLs?

I have a Django application where I store static images on Digital Ocean Spaces. Displaying these static images in my template is simple:<img>{% static 'images/my_image.png' %}</img> When I inspect the HTML page after loading, I see ...

Trouble with Angular localization module displaying codes instead of non-ASCII characters

I am currently utilizing a module from this source to facilitate localization efforts. However, I have encountered an issue where special characters are being displayed as their corresponding ASCII codes instead of their actual symbols. For example, &a ...

Even with employing Cors alongside Axios, I continue to encounter the following issue: The requested resource does not have the 'Access-Control-Allow-Origin' header

When working with a MEAN stack app, I had no issues with CORS. However, upon transitioning to the MERN stack, I encountered an error related to CORS despite having it implemented in the backend: Access to XMLHttpRequest at 'http://localhost:5000/api/ ...

Leverage Jasmine for testing a jQuery plugin

I'm currently utilizing the angular-minicolors library () within an angular controller: angular.element("myelement").minicolors({ position: 'top left', change: function() { //custom code to run upon color change } }) Wh ...

What are the distinctions between executing a c++ function and a JavaScript function?

After attempting to execute the c++ program provided below, a compilation error occurred. However, when trying to execute the second javascript code snippet below, no errors were detected. Why is this? ////c++//// #include<iostream> using namespace ...

Struggling to decide on the perfect CSS selector for my puppeteer script

I am trying to use puppeteer page.type with a CSS selector. <div class="preloader"> <div class="cssload-speeding-wheel"></div> </div> <section id="wrapper" class="login-register"> <div class="login-box"> <d ...

Discord.js version 13 encountered an issue where it is unable to access properties of undefined while

Having trouble with creating a warn system that just won't work! I've tried various solutions but nothing seems to be fixing it. Would greatly appreciate any help! Error Log: [FATAL] Possibly Unhandled Rejection at: Promise Promise { <reje ...

Are you using yeoman with csslint in your project?

As a newcomer to grunt, I am facing challenges in integrating csslint to monitor my project while running "grunt serve" for csslinting. I am specifically struggling with disabling the adjoining classes warning since it is not relevant for IE6 compatibili ...

Is it possible to stop an AjaxBehaviorEvent listener or send extra information to the f:ajax onevent function?

In the controller, I have created a listener that looks something like this: public class FooController { public void doSomething(AjaxBehaviorEvent evt) { closeDialogFlag = true; .. if(!isValid){ closeDialogFlag = f ...

Exclusion of specific numbers in the pattern

My task involves managing a list of exclusion numbers. For example, the following numbers are included in the exclusion list: (400276|400615|402914|404625) The pattern must prevent me from entering any of these numbers as the first 6 digits in the input ...

Error authorizing AJAX call to Gmail API

I'm just getting started with the GMail API and I'm attempting to use AJAX to fetch emails. This is my code: $.ajax({ beforeSend: function (request) { request.setRequestHeader("authorization", "Bearer xxxxxxxxxxxxxxxxx.a ...

Encountering a critical issue with Angular 12: FATAL ERROR - The mark-compacts are not working effectively near the heap limit, leading to an allocation failure due

After upgrading my Angular application from version 8 to 12, I encountered an issue. Previously, when I ran ng serve, the application would start the server without any errors. However, after updating to v12, I started receiving an error when I attempted t ...

Transforming an Angular 11 HTML template into Angular code

After attempting to transfer the Porto Admin HTML template to Angular, I encountered some issues. When including the CSS and JS dependencies in the project, everything worked fine with all the HTML code in index.html. However, when I moved the code to app. ...

Unable to render canvas element

Hey guys, I'm trying to display a red ball on the frame using this function but it's not working. I watched a tutorial and followed the steps exactly, but I can't seem to figure out what's wrong. Can someone please help me with this? I ...

Encountered an error trying to access property 'history' of an undefined value while using react-router v4 and create-react-app

I encountered an issue with using Link to navigate, here's the breakdown of my code: Directory structure components ----App.js ----home ----Home index.js index.js import React from 'react'; import ReactDOM from 'react-dom'; ...

The error message "Angular Animate - TypeError: undefined is not a function" indicates that

I seem to be encountering an issue when loading my Angular App. "TypeError: undefined is not a function" After a bit of investigation, it appears that the problem lies in declaring ngAnimate in my controller and I noticed the error originating from the A ...