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

Display a modal across all pages by incorporating a button component, regardless of its placement

I've implemented a header in my react app with a show dialog button that appears on all necessary pages. Currently, my approach to displaying the dialog is as follows: When the user clicks the button, I dispatch an action to the redux store { type:S ...

Troubleshooting AngularUI's UI-sortable Index Update Problem

I've encountered a strange bug while using AngularUI's ui-sortable directive. Most of the time, dragging elements works smoothly and the index is updated when an element is moved to a new position. However, there are instances where the index doe ...

What is the best way to dynamically change className in React.js?

I am working on a Collection component where I need to change the classNames of both the Collection component and its first sibling component when a div is clicked. Even though I tried using UseState, I could only manage to change the className of the cur ...

Guide to extracting a key from the route module with the help of vuex-router-sync

I have a Vuex store setup as shown below, and I am using vuex-router-sync to keep it in sync. This plugin adds a router module to my store. However, I am unsure of how to retrieve this object from the store since there are no associated getters with this m ...

In VueJS, v-slot is consistently null and void

Here is the issue at hand. Main view: <template> <div class="main"> <Grid :rows=3 :cols=4> <GridItem :x=1 :y=1 /> <GridItem :x=2 :y=1 /> </Grid> </div> </template> <scrip ...

Menu toggle vanishes suddenly

Whenever I click the toggle button, I notice that the menu (which I have set to appear on toggle) only shows for a brief moment before disappearing. As a beginner in bootstrap, I am sure I might have made some obvious mistakes. Any assistance would be gr ...

Facing continuous 404 errors while working with nodejs and express

While attempting to collect data from a local host webpage's registration form that captures user information, I encounter an issue upon pressing the submit button A 404 Error is displayed stating "page not found", preventing the collection and out ...

Exploring the wonders of Lightbox when dealing with content loaded via AJAX

Using Bootstrap 5 along with the Lightbox library from , I encountered an issue. The Lightbox feature functions properly on regular page loads, but fails to load on content loaded via AJAX. I attempted to resolve this by implementing the following code: ...

Showing VUE Content Delivery Network

Unable to render v-for with CDN in Vue.js const Gallery = { template: '{{$t('gallery')}} <img :class="[[item.class]]" v-for="(item, index) in carousel" :src="[[item.img]]" alt="img" />' } c ...

Disregard the Field File when utilizing jQuery validation

I have created a form with jQuery validation, but I am facing an issue where the file upload field is showing a message "enter no more than 3 characters." I believe this problem is due to the maxlength="3" property in the file field. How can I remove the ...

Issues Arise when Attempting to Upload Files to AWS S3 Using Node.js as

Utilizing this AWS S3 NPM Package for managing S3 uploads from my Express server has presented me with a puzzling situation. The uploader fails to trigger the end function. var key = utils.createID(Date.now()); var s3 = require('s3'); var client ...

No content in Axios response

axios.post( 'http://localhost:3001/users', { username:user.username } ).then((res)=> console.log(res.data)) Response From FrontEnd : data: &qu ...

Is it possible for using str_replace('<') to protect against code injected by users?

Recently, I've been working on a script that involves user input. In this script, I use echo str_replace('<', '&lt;', str_replace('&','&amp;',$_POST['input']));. It seemed like a solid f ...

Using JavaScript to launch a new window with an array of parameters

I am working on an asp.net mvc 3 application that has an Action Method for handling GET requests and returning a page. The code snippet is shown below: [HttpGet] public ActionResult Print(IEnumerable<string> arrayOfIds) { ....................... ...

What is the best way to retrieve a particular element from a dictionary?

In my dictionary structure, I have a list containing 2 dictionaries. Here is an example: dict: { "weather":[ {"id": 701, "main": "Mist", "description": "mist"}, {"id": 300, "main": "Drizzle", "description": "light intensity drizzle"} ] } If I wan ...

Is there another option besides PHP not being compatible with JavaScript?

I'm looking to dynamically change the properties of a div, so I've turned to using the jquery.keyframes plugin. The second class currently has a low-res blurred background image from the croploads directory. Now my goal is to switch it out for a ...

What is the best way to simulate a library in jest?

Currently, I am attempting to simulate the file-type library within a jest test scenario. Within my javascript document, this particular library is utilized in the subsequent manner: import * as fileType from 'file-type'; .... const uploadedFil ...

Creating a load more feature with Vue

Having some trouble implementing a load more button that adds 10 more items to the page when clicked. The button code seems to be causing issues as all items still appear on the page and there are no errors in the console either. As a result, the button is ...

What is the best way to handle receiving multipart/form-data in a Web API 2 using the OWIN pipeline?

I am encountering difficulties with properly handling the multipart/form-data post from ng-file-upload in my web api 2 method on the angular UI side. Here is how I am making the call: Upload.upload({ url: config.ApiUrl + 'Orders/Crea ...

Is there a way to accurately retrieve the width of an element within setInterval without any delay?

I'm currently experimenting with increasing a progress bar using the setInterval function. So far, it seems to be functioning properly. var progressBar = $('.progress-bar'); var count = 0; var interval = setInterval(function () { va ...