How can I handle a situation in Angular where there are multiple $http requests that are interdependent and need to

Let's talk about two different URL endpoints called "fruitInfo" and "fruitDetails"

The goal is to create an object with the following structure:

var fruitInfoDetails = {"fruitInfo": <contents of fruitInfo response data>,
"fruitDetails": <contents of fruitDetails response data>}

Within a service, the following code is executed:

var fruitInfoDetails = {};
this.getFruitInfo()
.then(function(data) {

   fruitInfoDetails['fruitInfo'] = data;
   this.getFruitDetails(data.nameOfFruit).then(function(data) {
        fruitInfoDetails['fruitDetails'] = data;      
   })
});

Assuming that this.getFruitInfo() and this.getFruitDetails() are functions that return promises using $http for each URL.

Looking for a more efficient way to achieve this? Ideally, a function that takes a list of fruits "[Apple, Pear, Orange]" and returns a list of fruitInfoDetails objects would be perfect.

Answer №1

If you want to create a custom promise using the $q service and resolve it after the second call is completed, you can follow this example:

angular.module('mymodule').factory('FruitService', function($http, $q) {
return {
    getFruitInfoDetails: function() {
        // create a new promise
        var deferred = $q.defer();
        // First API call
        $http.get("fruitInfo").then(function(fruitInfo) {
            // Second API call
            $http.get("fruitDetails").then(function(fruitDetails) {

                deferred.resolve({
                    fruitInfo: fruitInfo,
                    fruitDetails:fruitDetails
                });
            });
        });
        return deferred.promise;
    }
};
});

Alternatively, you can use $q.all() to wait for both requests to complete before resolving the promise, resulting in cleaner code with less indentation:

angular.module('mymodule').factory('FruitService', function($http, $q) {
return {
    getFruitInfoDetails: function() {
        // create a new promise
        var deferred = $q.defer();
        // First API call
        var infoPromise = $http.get("fruitInfo");
        var detailsPromise = $http.get("fruitDetails");

        $q.all([infoPromise, detailsPromise]).then(function(data) {
            deferred.resolve({
                fruitInfo: data[0],
                fruitDetails: data[1]
            })
        });

        return deferred.promise;
    }
};
});

This code snippet demonstrates how to retrieve a list of specified fruits:

angular.module('mymodule').factory('FruitService', function($http, $q) {

return {
    getFruitInfoDetails: function(fruit) {
        // create a new promise
        var deferred = $q.defer();

        // Assuming the fruit parameter is part of the API path
        var infoPromise = $http.get("fruitInfo/" + fruit);
        var detailsPromise = $http.get("fruitDetails/" + fruit );

        $q.all([infoPromise, detailsPromise]).then(function(data) {
            deferred.resolve({
                fruitInfo: data[0],
                fruitDetails: data[1]
            })
        });

        return deferred.promise;
    },

    getFruitList: function(fruits) {
        var deferred = $q.defer();

        // Map the list of fruits to a list of promises for fruit info
        var allPromises = fruits.map(function (fruit) {
            return this.getFruitInfoDetails(fruit);
        });

        // Wait for all promises to resolve before resolving our own promise
        $q.all(allPromises).then(function(allTheFruitInfoDetails) {
            deferred.resolve(allTheFruitInfoDetails);
        });
        return deferred.promise;
    }
};
});

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 following page shrouded in mystery is experiencing technical issues

Encountering some issues on the live server with this code. It's functioning perfectly fine on my local machine, but once I try to deploy it on Netlify, I'm running into this error message: ⨯ useSearchParams() should be wrapped in a suspense bo ...

Struggling to set the value for a variable within an Angular factory?

When dealing with a variable as an array, I have no trouble pushing objects inside and retrieving the values within the controller. However, when trying to directly assign an object to that variable, I run into issues. If anyone can assist me in achieving ...

Determine the success of an SQL query in Node.js

I've created a basic API using nodejs to connect my Flutter app with a SQL Server database, but I have a question. How can I verify if the query was successful in order to return different results? I'm attempting an update after a successful in ...

Utilize this JavaScript tool to effortlessly transform an XML string into JSON format

Looking for the optimal javascript function, plugin, or library to effectively transform an XML string into JSON format. One tool I came across is , but unfortunately, it struggles with strings that begin with 0. For example, 005321 may end up converted t ...

Modifying Input Types Using Javascript Within an HTML Table

I've managed to write some code that lets a user add rows to a table by clicking a button. Input fields are inserted into these rows. Now I'm wondering how I can set it up so that the first column has an input type of "text", while the middle col ...

Navigating the missing "length" property when dealing with partial functions generated using lodash's partialRight

I've been utilizing MomentTimezone for time manipulation within the browser. My development stack includes TypeScript and Lodash. In my application, there is an accountTimezone variable set on the window object which stores the user's preferred ...

Running a for loop with repeated calls to a Meteor method

My current setup involves using Meteor and AngularJS: ctrl.js for(var i = 0; i < result.length; i++){ Meteor.call('serverMethod', arg1, arg2, function(err, res){ console.log(res); }); } methods.js 'serverMethod' ( ...

highlight the selected option in the ng-repeat list of items

Looking for some assistance with a coding problem I'm having. I keep running into an error when trying to make a selected item in an ng-repeat list highlight. The CSS style is only applied on the second click, not the first. Additionally, I need to en ...

Create a bolded section within a TextField component using Material UI version 5

I am working with a TextField component that has a specific defaultValue set. Here is the code snippet: <TextField autoFocus={props.autoFocus} fullWidth defaultValue={props.defaultValue} value={text} onKeyPress={handleKey ...

Tips for sharing a global variable across numerous functions in various files

<script> var words = new Array(); words[1] = 'fresh'; words[2] = 'ancient'; </script> <script src="scripts/validation.js" type="text/javascript"></script> Additionally, in the validation.js file, we find: fu ...

What is the best way to ensure a string of words in HTML/CSS wraps to the next line seamlessly?

As I work on creating my portfolio website using Bootstrap and custom CSS, I am running into an issue with the game titles breaking in the middle when displayed. Despite my limited proficiency in English, I tried searching for a solution without success. ...

JavaScript library jQuery is unable to locate the element tagged as "<."

I've encountered an issue with setting the value of dropdown options in a web page using strings that contain < and >. Here is an example code snippet: <select id="m" name="m" > <option value="" selected="selected" >All</option& ...

"Observed Issue: Ionic2 Array Fails to Update in HTML Display

I am struggling with updating an array in Ionic2 and Angular2. I have tried updating it on the front end but it's not working, even though it updates perfectly on the backend (ts) as confirmed by checking the console. I need assistance with this. Her ...

Css shaky letters transformation

[SOLUTION] To resolve this issue, you can utilize the will-change CSS property that enforces GPU rendering: will-change: transform; [ORIGINAL QUESTION] After extensive searching on the internet, I have yet to find a solution to a seemingly simple prob ...

I am currently working on developing an HTML and JavaScript audio player that can play audio at specific scheduled times

Looking to create a custom HTML/JavaScript audio player that adjusts playback based on the time of day. For instance, if it's 1:00 pm, the file will start playing from 0:00 minutes; and if it's 1:01 pm, the file will begin playing from 1:00 minut ...

AngularJS: Issue with JQuery Slider not Updating Scope Value

I am currently working on a project using AngularJS and I have integrated a jQuery slider into it. However, I am facing an issue where I need to change the value of a select box which is defined in a $scope array, but the functionality is not working as ex ...

Unable to retrieve information from the firestore database

When trying to fetch documents from the firestore, I encountered an issue where it returns an empty array. However, when I run console.log(docs); outside of the declared function, it actually shows the array data. This problem arises because my useEffect f ...

The getElementById() function is unable to locate any matches on the current page

Below is the HTML code I am working with: import { currentSlide } from './Carusel'; <div className='app__mainpage'> <div className='app__mainpage_banners'> <img id='app ...

Performing a reverse image search request using Javascript/AJAX to query Google

I have been attempting to perform a reverse image search request using AJAX, but I keep receiving 302 errors. After checking the Firebug console, I discovered that the response header from Google contains a URL linking me to the results. However, I am unsu ...

The Angular carousel is malfunctioning

Excerpt from blue.json file: { "name": "blue", "version": "0.0.0", "dependencies": { "angular": "1.3.1", "json3": "~3.3.1", "es5-shim": "~3.1.0", "bootstrap-sass-official": "~3.2.0", "angular-sanitize": "1.3.1", "angular-anim ...