tips for efficiently loading JSON files using Angular

I currently have a situation where multiple controllers are calling the method getData() from a service. To prevent unnecessary duplicate http calls for the same json file, I have implemented the following approach:

QuizApp.service('quizService', ['$http', function($http) {
    var quizService = {},
        quizData;

    quizService.getData = function() {
        return quizData ? quizData : quizData = $http.get('quiz.json');
    };

    return quizService;
}]);

However, this implementation seems to be causing issues with displaying data on elements like sliders and thumbnail galleries using angular-slick. While there may be some problems at the moment, my main concern is whether the above code structure makes sense.

Alternatively, if I modify the getData() method as follows:

QuizApp.service('quizService', ['$http', function($http) {
    var quizService = {},
        quizData;

    quizService.getData = function() {
        quizData = $http.get('quiz.json');
        return quizData;
    };

    return quizService;
}]);

This second approach results in multiple http requests being made for the same json file, which does not seem ideal practice. However, it does seem to resolve the display issues with the angular-slick gallery. Although not consistently successful, sometimes random issues still occur with this method.

In general, disregarding specific contexts, which version of getData() seems more appropriate and why?

UPDATE

As mentioned by Mark, Angular has a built-in cache feature, but it is initially set to false. Refer to this post and this documentation for more information.

Even when caching the result of the http request, it seems to present similar issues encountered with the second option. Surprisingly, repeating the http request twice (as seen in the second code snippet) seems to work most of the time.

While caching the result provides consistency, it also means that the slick-angular functionality will never work correctly, prompting the need to explore alternative solutions.

Answer №1

Utilizing Angular $http's built-in caching feature can be beneficial in this scenario. You have the option to cache all $http requests, although this may not always be ideal, or you can choose to cache specific ones.

Here is a simple example of how you can implement caching:

quizService.getData = function() {
  return $http.get('quiz.json', {cache: true}).then(quizData => {
    return quizData;
  });
};

For more information on using caching with $http in Angular, refer to the Angular docs for $http

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

Unlocking the AngularJS variable within the template script

My controller code: $scope.totals = totals; In the template, I am able to successfully inject HTML using this code: {{totals}} However, my goal is to access the totals variable in a script within the template. Here's what I attempted: <script& ...

Creating a .json file using PHP and MySQL is a powerful way to

I'm having some trouble creating a json file using PHP on my Wordpress site. When I run the code below, I get an empty array -> {"posts":[]}. Can anyone provide me with some assistance? Thank you. $sql=mysql_query("SELECT * FROM wp_posts"); ...

Distinguishing Data Input Formats for REST WCF Services (JSON vs XML)

So, I am experimenting with WCF and creating a restful service. Currently, users are sending me data through http post requests in json format and I have one method set up to receive this data. But now I want to configure another method to be able to acce ...

Activate vertical scrolling in JavaScript when an image is clicked

I currently have a collection of button images with different hover effects specified like this: <img src="home.PNG" onmouseover="this.src='homemo.PNG'" onmouseout="this.src='home.PNG'" /> My goal is to make them scroll down to ...

What is the process for adding information to a MongoDB collection?

Working with NodeJS using Mongoose, I have defined two tables in db.js: const mongoose = require('mongoose') const UserSchema = new mongoose.Schema( { username: { type: String, required: true, unique: true }, email: { type ...

Is there a way to detect when the browser's back button is clicked?

As I work on supporting an e-commerce app that deals with creating and submitting orders, a user recently discovered a loophole wherein they could trigger an error condition by quickly pressing the back button after submitting their order. To address this ...

Determine in AngularJS whether there is a checked checkbox in a table row

Here is my HTML code snippet: <tbody ng-repeat="notification in notifications"> <tr> <td rowspan="{{notification.specs.length+1}}">{{notification.notification_id}}</td> </tr> <tr ng-repeat="position in ...

Is there a way to dynamically fetch and run JavaScript code from the server without resorting to the use of the

In my current project, I am developing a unique PHP framework that empowers PHP developers to effortlessly craft ExtJS interfaces containing forms, grids, tabpanels, and menus exclusively through PHP classes. To illustrate, creating a TabPanel in this fra ...

Unexpected results: jQuery getJSON function failing to deliver a response

I am facing an issue with the following code snippet: $.getJSON('data.json', function (data) { console.log(data); }); The content of the data.json file is as follows: { "Sameer": { "Phone": "0123456789", }, "Mona": { "Phone": ...

Cannot locate AngularJS + Typescript controller

I'm encountering an error while attempting to integrate TypeScript with AngularJS. The issue I'm facing is: Error: [$controller:ctrlreg] The controller named 'MyController' has not been registered Does anyone have any insights on what ...

Decompressing JSON data type document

I am currently facing an issue with deserializing a Json string to a custom class. Here is the structure of my json data: externDossierNr:"foo10" internDossierNr:"2016010" rapport:File testarray:Array[3] testword:42 __proto__:Object The fields externDoss ...

Issues with Google maps are causing multiple maps to malfunction

After incorporating some jquery code to create multiple maps upon window load, I noticed a peculiar issue with the maps - they all display the same location despite having different latitudes and longitudes set. Upon inspecting the code responsible for cr ...

Creating a Map Using HTML and JavaScript

My current project involves creating a simple map that can be moved with mouse drag functionality, featuring images such as islands. I have successfully retrieved the mouse position by declaring variables posX and e.clientX, as well as for e.clientY. Howe ...

Having difficulties understanding JSON and JSONP

I'm completely new to working with JSON and I am really struggling with making a cross-domain request. It's getting frustrating for me :( This is the code I currently have: $.getJSON('http://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0 ...

Troubleshooting: AngularJS 1.5 - Issue with ui-router when attempting to call a component within a state with no parent being recognized

Using angularJs 1.5 has posed a challenge for me. The issue I am facing is that when I attempt to call a state with a component, it does not seem to work. The TemplateURL does not load and I am unsure of what mistake I may be making. Below is the code sni ...

Tips for incorporating Angular2 into Eclipse using TypeScript

Recently, I delved into the world of Angular 2 and noticed that TypeScript is highly recommended over JavaScript. Intrigued by this recommendation, I decided to make the switch as well. I came across a helpful guide for setting up everything in Eclipse - f ...

Firebase notifications may appear duplicated when accessed from different browser tabs or when the browser is minimized

I have implemented Google's firebase for browser notifications and it is working well. The only issue I am facing is when I subscribe for notifications in a specific tab, and then switch tabs or minimize the browser, I receive two instances of notific ...

Tips for mocking a particular http resource (URL) solely in Angular

I'm part of a team with front-end and back-end developers. At times, the front-end team needs to make REST requests to an http address or REST-resource that hasn't been implemented yet. Within ngMockE2E, I've come across the $httpBackend se ...

Encountering a Javascript error while trying to optimize bundling operations

After bundling my JavaScript with the .net setting BundleTable.EnableOptimizations = true;, I've encountered a peculiar issue. Here's the snippet of the generated code causing the error (simplified): var somVar = new b({ searchUrl: "/so ...

What could be causing my Bootstrap datepicker to malfunction?

A while ago, my Bootstrap datetimepicker component was functioning perfectly in my code. However, it has suddenly stopped working and I am seeking assistance to get it running smoothly again. Below is the HTML code snippet: <script src="https://cd ...