Executing numerous HTTP requests within a single Angular JS controller

After creating multiple Drupal views to generate various JSON endpoints for different HTTP requests using Angular, I find myself in a situation where I have separate controllers for each request in my Angular script (as shown below). However, I am now looking to consolidate these requests into a single controller. I believe that utilizing $q, promises, or factories could be the solution, but I'm not entirely certain. Any assistance on this matter would be greatly appreciated. Thank you.

var module = angular.module('main',[]);
module.directive("masonry", function () {
    var NGREPEAT_SOURCE_RE = '<!-- ngRepeat: ((.*) in ((.*?)( track by (.*))?)) -->';
    return {
        compile: function(element, attrs) {
            // auto add animation to brick element
            var animation = attrs.ngAnimate || "'masonry'";
            var $brick = element.children();
            $brick.attr("ng-animate", animation);

            // generate item selector (exclude leaving items)
            var type = $brick.prop('tagName');
            var itemSelector = type+":not([class$='-leave-active'])";

            return function (scope, element, attrs) {
                var options = angular.extend({
                    itemSelector: itemSelector
                }, scope.$eval(attrs.masonry));

                // try to infer model from ngRepeat
                if (!options.model) {
                    var ngRepeatMatch = element.html().match(NGREPEAT_SOURCE_RE);
                    if (ngRepeatMatch) {
                        options.model = ngRepeatMatch[4];
                    }
                }

                // initial animation
                element.addClass('masonry');

                // Wait inside directives to render
                setTimeout(function () {
                    element.masonry(options);

                    element.on("$destroy", function () {
                        element.masonry('destroy')
                    });

                    if (options.model) {
                        scope.$apply(function() {
                            scope.$watchCollection(options.model, function (_new, _old) {
                                if(_new == _old) return;

                                // Wait inside directives to render
                                setTimeout(function () {
                                    element.masonry("reload");
                                });
                            });
                        });
                    }
                });
            };
        }
    };
});
angular.module('main',[]).controller('blogcontroller', function ($scope,$http) {
  $http.get('/blog-filter').success(function(result){
    $scope.blog = ( function () {
       return result.nodes;
    })();
  });
});


angular.module('cs',[]).controller('cscontroller', function ($scope,$http) {
  $http.get('/case-study-view').success(function(results){
    $scope.cs = ( function () {
      return results.nodes;
    })();
  });
});

Answer №1

Implement a factory that integrates all $http services and utilizes $q in the following manner:

(function(){
    app.factory('CountriesServices', countriesServices);
    countriesServices.$inject = ['$http', '$q', 'settings'];

function countriesServices($http, $q, settings) {
    var self = {};

    self.getCountries= function(){
        var deferred = $q.defer();
        var url = settings.baseService + 'api/country';

        $http.get(url)
            .success(deferred.resolve)
            .error(deferred.reject);

        return deferred.promise;
    };

    self.getCountry = function(id){
        var deferred = $q.defer();
        var url = settings.baseService + 'api/country/' + id;

        $http.get(url)
            .success(deferred.resolve)
            .error(deferred.reject);

        return deferred.promise;
    };



    return self;
}
})();

Answer №2

Definitely consider placing your $http requests within a factory in Angular:

angular
  .module('sharedServices')
  .factory('dataRepository', dataRepository);

dataRepository.$inject = ['$http', '$q'];

function dataRepository($http, $q) {
  var service = {
    getData: getData
  };

  return service;

  function getData() {
    var deferred = $q.defer();
    $http.get('/data').success(function(response){
      deferred.resolve(result);
    });
    return deferred.promise;
  }
}

Then, in your controller:

dataRepository.getData().then(function(data) {
  $scope.data = data.results;
});

Repeat the same pattern for any additional $http calls you need to make.

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

Issues with Opera Mini Jquery AJAX not loading

I recently created a website optimized for mobile devices, but I'm encountering an issue with AJAX calls specifically on Opera Mini. One particular request involves loading additional content when the user scrolls to the end of the page (70%). $(docu ...

How come my ajax function is not processing when the form is submitted?

Having an issue with validating a form where I need to check if a username is available before submission. Although all functions, including the PHP script for checking the username, are working properly, I'm unable to prevent the form from submitting ...

Ask the user through a personalized pop-up window if they want to continue navigating without saving their data

Is it possible to create a customized prompt when the user clicks on a different link without saving edited data? Currently, I am using window.onbeforeunload and it works fine, but I would like to have a personalized prompt instead of the default browser ...

When the document is shifted by an angular function call, the mouseup event fails to trigger

My problem involves an angular function that alters the ng-if state to display the sidebar when the image is clicked. However, upon calling the function and shifting the entire webpage, the mouseup event for the image no longer triggers when I release th ...

Failure [ERR_STREAM_WRITE_AFTER_END]: writing past the endpoint [npm-request using socket.io]

My server has a socket server running, and on my laptop, I have a socket.io-client service. When both are turned on, they establish a connection. When other users request information from my server, the server sends that request to my laptop via a socket. ...

After mapping the elements of the array twice, generate a new array

Two differently formatted bits of data may be received, each requiring different character stripping methods. The variable names are temporary and will be changed once the function is operational. const cut = flatten.map(obj => { return obj.file. ...

Querying for specific data in MongoDB using a combination of document ID and values within an

Trying to create a function that can search for an object based on its ID and if a specific value is present within an embedded array. { "_id" : ObjectId("569bea91c0e1fee4063527ac"), "user" : ObjectId("568c65174fee132c36e199dd"), "votes" : 9, "image" ...

Choosing multiple options in a dropdown menu that updates dynamically according to the selection made in another dropdown

Is there a way to enable multi-select in a dynamically populated dropdown based on the selection of another dropdown? I have two dropdowns on my page. Initially, the second dropdown is empty. When a value is selected in the first dropdown, the options in ...

ExpressJS and Angular: Issue with Loading the Index Page

I'm encountering a challenge while working on an application that incorporates expressjs and angular. The setup involves loading angular, bootstrap, and other libraries from the index page. During testing, I added a button <a ui-sref=about>about ...

Having issues with Twitter typeahead bloodhound tokens not functioning properly

Why are the tokens not working? I expect 'Inkoopverenigingen' to be suggested when typing 'east', 'home', or 'trap'. json: [ { "value": "Inkoopverenigingen", "tokens": [ "inkoopverenigingen", ...

Secure access to an API using a certificate within a Vue.js application running on localhost

My vue.js app is built using vue-cli. The application is hosted at dev.example.com and the REST API can be found at dev.example.com/api/v1/. The backend has added an SSL certificate for security on the development environment. However, when I try to make a ...

Adapt your content to match the current slide of the dynamic Bootstrap Carousel

I recently implemented the basic carousel from the bootstrap website into my web application and encountered a challenge. I want to adjust the content on my site based on the active slide of the carousel... is this achievable? My goal is to display div On ...

The deviceorientation event in JavaScript is not triggering on Chrome for Android

I am attempting to activate the deviceorientation event in JavaScript, but it's not firing on my Android device. If you'd like to review the event documentation, please click here and view this image: https://i.sstatic.net/HkcOQ.png window.addE ...

Executing Python scripts with libraries using Node.js

A Node.js application I have in place conducts GET requests to an API every minute. The acquired data is then stored in a MongoDB database. Simultaneously, the Node.js app initiates and runs a Python script using the Keras library on this data at the same ...

The message "jest command not recognized" appears

My test file looks like this: (I am using create-react-app) import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Calculator'; import { getAction, getResult } from './actions/' ...

Restangular failing to apply headers during post requests

I have been encountering an issue while trying to set the header for a single post request using Restangular. Despite following the documentation here and seeking help from a similar question, the request is being sent as plain text instead of JSON. My se ...

Dynamically Generate HTML Elements with jQuery

My current goal is to generate an HTML element using JavaScript with jQuery by pulling information from an Array of Objects that contain details like the element tag, class, and other attributes or styles. What are the Benefits of Using jQuery over Raw HTM ...

Loopback Model Property Somehow Resurrected After Deletion

Within my function, I am working with an object called 'ctx.instance' that contains various properties: firstName: 'Ron', lastName: 'Santo', minor: true, accepted: false, emailChanged: false, organizationId: 00000000000000000 ...

Selenium's pop-up error message stating that "</button> is not clickable at point"

Although similar questions have been asked in the past, I have not been able to find a solution that works for me when trying to scrape data from air.norfolk.gov. The annoying disclaimer popup at the beginning is causing issues and I just want to get rid o ...

Array with multiple dimensions and time stamps

Below is the code snippet : const eventArray = []; $('.body-watch-logo').each(function() { let eventObj = {}; eventObj['eventId'] = $(this).data('event'); event ...