Constantly retrieving AngularJS JSON data on the details page

Simply put, I have developed a 2-page AngularJS application because I am integrating it into CMS templates and a single page app would not work well with the CMS widgets in the sidebar.

On my results page, I am pulling data from 3 different JSON files using AngularJS 1.5.x factory and $q services, all managed by a controller named EventsListCtrl.

Clicking on an item takes users to a details page which is another single page app utilizing AngularJS. The details page extracts variables from the URL to retrieve specific data from the appropriate JSON file, controlled by a different controller called EventDetailCtrl.

Despite needing only one JSON file based on the URL parameters, I observed that all three JSON files are being pulled. How can I prevent unnecessary requests for additional JSON files?

The goal here is to enhance page load speeds by stopping the retrieval of unrequired JSON files.

An excerpt from my detailed controller is provided below:

// Event Detail Page
    function eventDetailCtrl(MyService, $filter){
        var vm = this;

        vm.eventStatus = 'Loading';
        vm.eventId = window.location.toString().split('?id=')[1].split('&ref')[0];
        vm.noResults = '<h4>Sorry, something went wrong.</h4>The page you requested could not be found.';

        activateEventDetail();

        function activateEventDetail(){
            MyService.getEventData.then(
                function(response){
                    vm.eventResults = response;
                    vm.eventId = $filter('filter')(vm.eventResults,{Id: vm.eventId})[0];
                    vm.eventStatus = 'Success';
                    if(vm.eventId != undefined){
                       window.document.title = "Network West Midlands - Event: " + vm.eventId.Title;
                    }else{
                        vm.eventStatus = 'Error';
                        window.document.title = "Network West Midlands - Event: " + 'Sorry';
                    }
                },function(error){
                    vm.eventStatus = 'Error';
                    console.log('EventDetail Error: ' + error.statusText);
                }
            );
        }
    }

MyService is a factory utilizing standard promise techniques as shown below:

.factory('MyService',['$http','$q', myService]);

    function myService($http, $q){
        var eventfulData = $http.get('FutureEvents', {cache: 'true'});
        var googleData = $http.get('WmPlacesList', {cache: 'true'});
        var facebookEvents = $http.get('FacebookNwm', {cache: 'true'});

        return {
            getEventData: getData(eventfulData),
            getAttractionData: getData(googleData),
            getfbEvents: getData(facebookEvents)
        }

        function getData(jsonData){
            /* Just a generic deferred object that we will resolve manually. */
            var defer = $q.defer();
            $q.when($q.all([jsonData])).then(getDataComplete,getDataFail);

            return defer.promise;

            function getDataComplete(response){
                var finalData = response[0].data;
                defer.resolve(finalData);
            }

            function getDataFail(response){
                defer.reject(response);
            }

        }
    }

Answer №1

There are multiple issues that need to be addressed

   return {
        getEventData: getData(eventfulData),// invokes getData()
        getAttractionData: getData(googleData),
        getfbEvents: getData(facebookEvents)
    }

The current implementation is invoking getData without passing it as a reference, resulting in 3 separate requests being made.

A better way to write the code would be:

return {
  getEventData: function() {
    return getData(eventfulData);
  },
  getAttractionData: function() {
    return getData(googleData);
  },
  getfbEvents: function() {
    return getData(facebookEvents);
  }
}

Using $q in getData() is unnecessary since $http already returns a promise. The function can be refactored like this:

function getData(jsonData) {
  return jsonData.then(getDataComplete)
                 .catch(getDataFail);    
}

function getDataComplete(response) {
  return response.data;
}

function getDataFail(response) {
  // Handle errors as needed
}

To call MyService.getEventData from the controller, you should modify the invocation like this:

Instead of:

MyService.getEventData.then(

Use:

MyService.getEventData().then(

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

Using React, we can create a component by defining it as a constant and then

Currently, I have a React component that is created as a const and takes props. In another file, there is a function called selectChanged() {} which returns undefined every time the select value is changed. The code for the component is as follows: ... ...

Click event recursion occurs due to the use of $.post

I have a collection of product rows available for customers to select from. Each row is designated with the class "product-line". Upon clicking on a row, I aim to visually indicate its selection status by toggling the "product-checked" class, and subsequen ...

The AngularJS view refuses to load when accessed from the browser, although the identical code successfully loads the view on

Here is the link to my plunker where the view loads as expected on Plunker's website. Check out My First Angular Single Page Application However, after downloading the files from Plunker and unzipping them on my local machine, the view does not load ...

Navigating through deeply nested JSON data using Python

I am attempting to extract the IDs from a JSON using Python. Here is the code snippet: import requests import json import csv headers = { "Authorization": "" } r = requests.get("https://discordapp.com/api/v6/users/@me/relations ...

How to Decode JSON information using C#

There is a JSON data structure {{ "action": "rma", "devices": "[95001105,30013103,300117]", "devandreason": [ { "device": 95001105, "reason": 100 }, { "device": 30013103, "reason": 300 }, { "device": 300117, ...

Accessing MongoDB Collection with AngularIncorporating Angular to

My MongoDB Collection has the following structure: { "Auftragsnr" : "456", "Positionnr" : "Babba Jabba Frabba", "__v" : 0, "_id" : ObjectId("53d8ef77888a15ed69dd16a5") } { "Auftragsnr" : "123", "Bonusposition" : "test", "Geschaeftsfeld" : "test3", "Posit ...

While attempting to deploy my project on Vercel by pulling in my code from GitHub, I ran into this error

As a self-taught Front End developer diving into building and hosting my first web page using React, I've encountered this warning. Any suggestions on how to resolve it? Cloning gitohub.com/Passion94/React-Apps (Branch: main, Commit: da89a2a) Cloning ...

$watchCollection not firing when object is modified

I've been trying to understand why the watchCollection function is not triggering on object changes. .factory('Products', function($http, $timeout){ function Products(data){ if (data) { this.setData(data); ...

Animation failing to be queued properly

Here is a snippet of code that moves a heading icon back and forth when you hover over the heading: jQuery('h1.heading').hover( function(){ $icon = jQuery('.heading-icon', this); if( ! $icon.is(':animated') ){ ...

Tips for modifying the value and refreshing the array

I retrieve data from $scope.roleinfo = {"QA":[{"White Box Testing":0},{"Black Box Testing":0}],"Development":[{"Server Side":0},{"UI":0},{"Back end":0}]}; Then, I present these values in a table. Now, I need to update the maxcount and create an array w ...

JavaScript enables users to store over 5 megabytes of data on their client devices

Is there a way to store more than 5mb in the client browser? I need this functionality across various browsers including Firefox, Chrome, Internet Explorer, Safari (iOS), and Windows Phone 8 Browser. Initially, localStorage seemed like a viable option as i ...

Enhancing the Security of Spring Rest Services: A Guide to Implementing Spring Security with AngularJS

I currently have a setup with a Spring MVC Server Backend hosting Rest-Services and an AngularJS WebFrontend. I'm looking to enhance the security of my spring mvc rest services, but I want to implement it using Java config. However, I am unsure about ...

Utilizing variable query operators solely in instances where they hold value

Imagine you are on a movie website where you can customize filters for the movies displayed to you. Currently, these preferences are stored in the User model as a map. Here is an example of what the preferences object might look like: preferences: { yea ...

Testing the custom directive controller with Karma and Jasmine

Attempting to conduct a test on an AngularJS custom directive using Karma + Jasmine has proven to be quite perplexing. After scouring various resources online, I came across a method that seems to work, but it doesn't feel like the right approach. Let ...

I developed a callback API designed to receive JSON data, however, it seems to be malfunctioning

I've set up a callback API to fetch the JSON data from my server, but it doesn't seem to be working as intended. This is the response I should be getting in my API {"ERROR":0,"STATUS":1,"ORDERID":753093,"OPTRANSID":"2107938600"} I've crea ...

In a React app, there are instances where `localstorage.getitem('key')` may result in returning null

I've encountered a strange issue while building a login form that sets a JWT token in localstorage. The problem arises when, despite being able to see the token in my console.log, setting localstorage.getitem('idToken') sometimes returns nul ...

What is the best way to use AngularJS to extract values from the first dropdown menu that are linked to the values selected in the second

How can I link values in two dropdowns using AngularJS? Hello everyone, I have set up two dropdown fields in MyPlunker and within the ng-option tag, I have applied a filter like filter:{roles: 'kp'} to only display users with the role of kp. T ...

Charts.js fails to refresh data following an AJAX call

Having recently delved into the world of js and jquery, I managed to successfully display a chart using Flask and an Ajax request. However, I've hit a roadblock when it comes to refreshing the charts data. If I create a new chart each time as demonstr ...

How can the CORS issue be resolved when sending a form from a client to an AWS API gateway function?

Within my front end React application, I am looking to implement a contact form that will submit data to a Lambda function via an API Gateway with a custom domain attached. The frontend operates on the domain dev.example.com:3000, while the API Gateway is ...

What is the best method for sending a GET request with JSON body using JMeter?

Currently, I'm encountering a problem where JMeter is not recognizing the JSON body that is being passed as a parameter. Interestingly, when I tested it using Postman, everything was working smoothly. However, with JMeter, the issue persists. My expe ...