Verifying the presence of JSON data loaded directly from the server to decide whether the factory should initiate a request to retrieve the same data if it is not already available

I am currently developing an Angular application that is designed to load a JSON object from the server on page load, either freshly or if it doesn't already exist. I'm wondering how one could use a service or factory to check for the presence of this JSON object on the page. If it is found, the app should use that data and inject it into the controller. However, if the JSON object is not present, the app should make a request to the server to retrieve it.

For example:

var data = {item1: foo, item2: bar, item3: baz}

If this data exists on page load, Angular will utilize the 'data' variable as the foundation to construct the model. But if the data is not available, the app would then contact the server to obtain the same object and use that information instead.

While I am still relatively new to Angular, I have acquired enough knowledge to understand how to perform AJAX requests and properly bind returned data. In this specific scenario, my main inquiry is regarding the appropriate method to verify the existence of data in order to determine whether a call to the server is required during app execution.

Answer №1

To efficiently manage data retrieved from an API, you can utilize $cacheFactory in AngularJS to create a cache singleton.

var app = angular.module('myApp', []);

app.factory('cache', function ($cacheFactory) {
    var cache = $cacheFactory('myCache');
    return cache;
});

app.factory('myFactory', function (cache) {
    return {
        getData: function () {
            if (cache.get('mydata') !== undefined) {
                console.log('Retrieving from cache...');
            } else {
                cache.put('mydata', {
                    item1: 'foo',
                    item2: 'foo'
                });
                console.log('New data added to cache.');
            }
            return cache.get('mydata');
        }
    }
});

function Ctrl($scope, myFactory) {
    myFactory.getData() // New data added to cache.
    myFactory.getData() // Retrieving from cache...
    myFactory.getData() // Retrieving from cache...
}

View Working Demo

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

The URL in React Router updates as expected, but when attempting to render a component using a button component link

I have encountered a situation similar to the one portrayed in this CodeSandBox example, where I am required to implement react routing within two distinct components. The issue that is perplexing me is that, when I navigate down to either the Profile or ...

Retrieving data from a nested object with varying key names through ng-repeat

My JSON object contains various properties with unique names: var definitions = { foo: { bar: {abc: '123'}, baz: 'def' }, qux: { broom: 'mop', earth: { tree: 'leaf', water: 'fi ...

My goal is to prevent users from using the Backspace key within the input field

Let's say we want to prevent users from using the backspace key on an input field in this scenario. In our template, we pass the $event like so: <input (input)="onInput($event)"> Meanwhile, in our app.component.ts file, the function ...

My goal is to have the "show more" button reveal extra information without having to reload the entire page

I’m trying to figure out how to make the “more” button show additional information without reloading the entire page. I’ve done some research online and found that AJAX can help with this, but since I’m just starting to learn JavaScript, I have n ...

The node.js express app.get and app.post are currently malfunctioning

I have encountered an issue with my Express JS code. Currently, I am using app.use and everything works perfectly. However, when I try to use app.post or app.get instead of app.use, the code stops working and my IDE (WebStorm) does not recognize these meth ...

How can we extract validation data from a function using Ajax and then transfer that information to another Ajax query?

I have an AJAX function that validates a textbox on my page. After validating, I need to perform an action with that value (search in the database and display results in the textbox). However, I also need the validation function for another separate functi ...

Experimenting with Vuejs by testing a function that delivers a Promise upon the execution of the "Created" hook

In my Vuejs application, I have the following script written in Typescript: import { Foo, FooRepository } from "./foo"; import Vue from 'vue'; import Component from 'vue-class-component'; import { Promise } from "bluebird"; @Component ...

Angular failing to reflect changes in my select element according to the model

One issue I'm facing in my application is with grouped select elements that share the same options. Whenever one select element changes, it checks the others to see if the new option selected has already been chosen in any of the other selects. In suc ...

PHP - WebCalendar - Show or Hide Field According to Selected Item in Dropdown List

Working with the WebCalendar app found at to make some personalized adjustments to how extra fields function. I've set up two additional fields: one is a dropdown list of counties, and the other is a text field. Within the dropdown list, there is an ...

Inserting star ratings into a MySQL database using a form and AJAX request

I am in the process of creating a feedback application for a tablet using phonegap-android. The main page features a registration form, while the secondary page includes a star rating with six questions that the user needs to rate. I aim to store the resul ...

Issue encountered when invoking the callback function in Node.js with console prompt libraries

Whenever I work with libraries that allow me to input data into the console, I always encounter a bug that prevents me from properly using callback functions. The issue is that the callback works fine without the data input part, but when I try to use it w ...

The TypeAhead feature fails to display any search results for the entered query

Feeling really desperate right now! I'm facing a frustrating issue with Bootstrap Typeahead. Here is the HTML Markup: <div class="form-group"> <label for="">Recipients</label> <input id="recipients" name="recipients" ...

I'm having trouble accessing the data stored in req.user within the user controller, despite having integrated it into the user isLoggedIn middleware

I am encountering an issue where I cannot access my req.user in the usercontroller, even though I have implemented it in the usermiddleware. Both storing data in req.user and retrieving data using req.user from the middleware to my controller are not work ...

The download attribute is not functioning properly on both Chrome and Edge browsers

I've been trying to use the download attribute, but it doesn't seem to be working. I have also attempted to use the target attribute to see if there are any issues with downloading from the server or from a web (https) source. Unfortunately, noth ...

Encountered an undefined error while trying to read promises

I'm attempting to receive a response from a function in order to trigger another function, but I am not receiving the expected response. I encountered the following error message: "TypeError: Cannot read property 'then' of undefined." In my ...

Retrieve props in a Vue component using the available context

As a newcomer to the VUE world, I have begun creating an app to display a list of TODO's. Passing the todo items through props to the todo component felt like the right approach, but I found myself searching for a more efficient way to share props wit ...

The functionality of activating a button is not functioning as expected in AngularJS framework

Next to the question I have linked here, I am exploring a different approach. As a beginner in AngularJS/Cordova/Ionic, my goal is to achieve different outcomes when the "Eingepasst" button is clicked, each with unique logic compared to "Gewonnen" or "Ver ...

Steps for calling a function in index.js using Node.js

I am just starting to learn about NodeJS and I have a question that might seem basic to some, but I would really appreciate some assistance here. Here is the content of my index.js file:- 'use-strict'; const { myauth } = require('./src/au ...

The validation errors in the form of CodeIgniter are not being displayed by the JavaScript variable

Currently, I am utilizing the built-in validation_errors() function in CodeIgniter for my login form. The validation errors are displaying correctly in my view, but when I try to echo them into a JavaScript variable within the script to customize notificat ...

Plugin for turning text into "leet speak" using jQuery and Javascript

Recently, I've been on the hunt for a 1337 translator that I can seamlessly integrate into a jQuery plugin. While I believe I'm making progress, I can't shake off the feeling that something's amiss. My gut tells me that what I currently ...