Troubleshooting problems with displaying views due to asynchronous $http.get calls in AngularJS

Within my application, I am utilizing two separate API calls. The initial call retrieves a catalog of services along with their unique ID's. Subsequently, once the ID information is acquired, a second call is made to retrieve pricing data for each corresponding service. However, a pressing issue has arisen where the second GET request is being excessively triggered on each page load, leading to memory problems in browsers like Chrome and Firefox.

The following code snippet reflects my view setup:

<tr ng-repeat="c in catalog track by $index">
    <td>{{ c.id }}</td> 
    <td>{{ c.name }}</td> 
    <td>{{ c.description }}</td> 
    <td>{{ c.service_status }}</td> 
    <td>{{ getService(c.id) }} {{services}} </td>  
</tr>

My API calls are structured in factories using promises as outlined below:

app.factory('catalogDataFactory', function($http){
    var getCatalog = function() {
        // Sample API call response
        return $http.get("../data/catalog.json").then(function (result){
            return result.data;
        });
    };
    return { getCatalog: getCatalog };
});



app.factory('servicesDataFactory', function($http){

    var service = {};
    var baseURL = '../data/'; 
    var _guid = '';

    service.setGuid = function(guid){
        console.log("setGuid is being called multiple times with input: " + guid);
        _guid = guid;
    }

    service.callAPI = function(){
        console.log("callAPI is being invoked too frequently");
        return $http.get(baseURL + _guid + ".json").then(function (result){
                return result.data;
        });

    }

    return service;
});

The structure of my controller is as follows:

app.controller('customersCtrl', function($scope, $compile, catalogDataFactory, servicesDataFactory, utilities) {

    $scope.catalog = []
    $scope.service = [];

    catalogDataFactory.getCatalog().then(function(result) {
        $scope.catalog = result.data[0]['services'].data; 
        console.log("getCatalog is being called excessively"); 
        $scope.getService = function (guid){
            console.log("getService is being invoked too many times"); 
            servicesDataFactory.setGuid(guid);
            $scope.service = servicesDataFactory.callAPI();
        };

    }); 

}); 

An error message I am encountering is https://docs.angularjs.org/error/$rootScope/infdig?p0=10&p1=%5B%5D, causing browser freezing and numerous repetitions of the same errors in the console logs.

Given these circumstances, I pose the question whether switching from a factory to a Service for the second API call would be more beneficial, or if fundamental changes are necessary within the code?

Answer №1

It is not recommended to invoke a function within an ng-repeat loop as it will result in the function being called with every $digest cycle. This can lead to multiple calls when there are scope changes or HTTP callbacks triggering updates.

Instead of using a getService method, you should consider returning a dictionary of catalogs and their services from the server or constructing one when the controller is initialized. Then, within the ng-repeat loop, you can simply access the service value directly from this centralized dictionary.

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

What is the process for sorting Google Map markers with AngularJS?

.controller('MapCtrl', ['$scope', '$http', '$location', '$window', '$filter', '$ionicLoading', '$compile','$timeout','$ionicPopup', function ...

In the MUI v5 framework, when using nested modals, both the parent and child modal instances will close simultaneously

Here is the reproduction of my issue on codesandbox: https://codesandbox.io/s/trusting-babbage-ovj2we?file=/src/App.js A nested modal has been created where the parent modal opens a button leading to the child modal. The useState of the parent modal has b ...

Filter the object by its unique identifier and locate the entry with the highest score

I'm currently working on figuring out the proper syntax for sorting an object by ID and then identifying the highest score within that ID array. While I've managed to sort the object up to this point using conditionals and the sort() method, I&ap ...

Is it possible for an image to be displayed in another div or table column when I hover my mouse over it?

I am looking to create an image gallery with thumbnails on the left side. When I hover over a thumbnail, I want the full image to be displayed in another section on the page. Can anyone provide me with the correct code or suggest a plugin to achieve this f ...

How can I access a component variable within a foreach loop in Typescript?

Can anyone please explain how I can access a component variable within a foreach loop? Check out my code on Plunker public exampleVariable:number; test(){ console.log('fired'); var x =[1,2,3,4]; x.forEach(function (e){ th ...

Setting attributes to a DOM element using String in jQuery

I am currently facing a challenge where I have a list of attributes saved as a string variable, and I need to add that variable to a <div>. Unfortunately, I am stuck and uncertain about the best approach. Here is what I have so far: HTML: <div&g ...

Examining the scroll-down feature button

I'm currently experimenting with a scroll down button on my website and I'm perplexed as to why it's not functioning properly. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" c ...

Encountering issues with integrating colors into a JSON file within style-dictionary

I am looking to utilize the style-dictionary npm package to generate scss vars from my design token, without using the cli. Currently, I have a single token that encompasses the entire design system, and I cannot guarantee separate json files from the desi ...

Simulating an ES6 module that returns a factory function for moment.js

Disclaimer: I'm a beginner with Jest so please bear with me. I'm currently working on testing a Vue2.js filter named DateFilter using Jest. This filter simply formats a date that is passed to it. DateFilter.js import Vue from 'vue'; ...

Using ReactJS to create different behavior for checkboxes and rows in tables with Material-UI

I am looking to customize the functionality of checkboxes and table rows. Currently, clicking on a row also clicks the checkbox, and vice versa. What I would like to achieve is for clicking on a row to trigger a dialogue box, and for clicking on the chec ...

Exploring strings and JSON manipulation in Python: the art of json.loads and json.dumps

Here's the string I have: results = "{'eventid': '766', 'category': '0', 'uptime': '0', 'severity': '0', 'traptime': '0', 'formatline': ...

The login controller fails to retrieve any values upon submission

My current controller setup looks like this: var myApp = angular.module('myApp', ['ui.router']); myApp.controller('loginController',['$http', function($http) { this.loginForm = function(){ console.log(th ...

Prevent scrolling to the top when using router.push in Next.js

Currently, I am utilizing the router feature from Next.js by importing useRouter from next/router. I am currently facing an issue where the page automatically scrolls to the top when changing the query parameters in the URL. Is there a solution available ...

Working with arrays containing numerical keys in JSON using jQuery

If I have a PHP file that generates JSON data with numerical keys like this: <?php $array[1] = "abcd"; $array[2] = "efgh"; $array[3] = "1234"; $array[4] = "5678"; echo json_encode($array); ?> How can I access the value associated with key 4? The i ...

How can a dialog be displayed using a template in Onsen UI in a proper manner?

I am having trouble displaying a dialog in my Angular app with Onsen UI 1.3.6. Whenever I try to show the dialog, I encounter a 404 Not Found error. This is the JavaScript code I am using: ons.createDialog('iconselector.html').then(function(dl ...

Separating buttons (two buttons switching on and off simultaneously) and displaying the corresponding button based on the data

My current project involves creating a registration page for specific courses. While I am able to display the information correctly, I am facing an issue with the ng-repeat function. The problem lies in all the Register buttons toggling incorrectly. Additi ...

The countdown timer resets upon the conditions being rendered

I have been using the 'react-timer-hook' package to create stopwatches for each order added to an array. The problem I encountered was that every stopwatch, across all components, would reset to zero and I couldn't figure out why. After a lo ...

Performing AJAX requests within AJAX requests without specifying a callback function for success

Upon reviewing this discussion jQuery Ajax Request inside Ajax Request Hello everyone, I'm in need of some clarification on a particular scenario. I recently took over the code from a former member of my development team and noticed that they have ma ...

Replace Formik with useFormik to streamline your code

I have implemented Formik/Yup for validation on a page that triggers a GraphQL mutation. The code is functioning as expected: export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); const [isRemoved ,setIsRemo ...

Send JSON data from a .json file to a Vue component via Express, then store it in a variable

How can I display data on my webpage that is stored in a dsa.json file? My setup involves using express with vue. Below is the code snippet from server.js: var data; fs.readFile('./dsa.json', 'utf8', (err, data) => { if (err) th ...