Can angular $q.all() achieve the same level of success as jQuery $.get()?

Upon reviewing the jQuery documentation, I discovered the following:

$.get( "example.php", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" ); <---
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });

Now, in my Angular controller, I have a requirement to execute a method after making multiple ajax calls. Here's an example of what I want to achieve:

 $q.all([
            $http.get(ROOT + "Lookup/GetStates"),
            $http.get(ROOT + "Lookup/GetCountries"),
            $http.get(ROOT + "Address/GetAddresses"),
        ]).then(function (results) {
            $scope.states = jQuery.parseJSON(results[0].data.data);
            $scope.country = jQuery.parseJSON(results[1].data.data);
            $scope.addresses = jQuery.parseJSON(results[3].data);
        });

Following the then execution, specifically (only after the then), I need to invoke a method called $scope.setupControls().

Is there a way to accomplish this?

Answer №1

Why was it not possible to accomplish this task:

   $q.all([
        $http.get(ROOT + "Lookup/GetStates"),
        $http.get(ROOT + "Lookup/GetCountries"),
        $http.get(ROOT + "Address/GetAddresses"),
    ]).then(function (results) {
        $scope.states = jQuery.parseJSON(results[0].data.data);
        $scope.country = jQuery.parseJSON(results[1].data.data);
        $scope.addresses = jQuery.parseJSON(results[2].data);
        $scope.setupControls();
    });

I believe there is no necessity for a second success. Let's keep it simple (and perhaps sexy?).

Answer №2

Take a look at the following code snippet:

.finally(function() {
  // perform this action regardless of success or error
});

This code block executes after both success and error scenarios.

Here is the full code snippet:

$q.all([
        $http.get(ROOT + "Lookup/GetStates"),
        $http.get(ROOT + "Lookup/GetCountries"),
        $http.get(ROOT + "Address/GetAddresses"),
    ]).then(function (results) {
        $scope.states = jQuery.parseJSON(results[0].data.data);
        $scope.country = jQuery.parseJSON(results[1].data.data);
        $scope.addresses = jQuery.parseJSON(results[3].data);
    }).finally(function() { /* <-- Action performed here */
      // Perform this action on both error and success cases
    });

Answer №3

When working with Angular, the $q service offers similar functionality to jQuery. More information can be found here.

An approach that comes to mind is as follows:

$http.get('parent request')
.then(function(win){
      // execute actions once everything is resolved
   },
   function(err){
      // handle errors
   },
   function(progress){
      // carry out tasks when a child request is resolved
   }
);

In this scenario, the "parent request" triggers multiple child requests. For each successfully resolved child request, you can utilize the .notify() method to update the parent request. It is also important to keep track of the status of all child requests, and once they are all resolved, call .resolve() to proceed with your desired actions (such as $scope.setupControls() in your specific case).

Answer №4

It is possible to call the then method multiple times for chaining promises.

https://docs.angularjs.org/api/ng/service/$q

Creating a Chain of Promises By calling the then method of a promise, a new derived promise is returned, allowing for a chain of promises:

promiseB = promiseA.then(function(result) {
   return result + 1;
});

// promiseB will be resolved immediately after promiseA is resolved and its value
// will be the result of promiseA incremented by 1


$q.all([
        $http.get(ROOT + "Lookup/GetStates"),
        $http.get(ROOT + "Lookup/GetCountries"),
        $http.get(ROOT + "Address/GetAddresses"),
    ]).then(function (results) {
        $scope.states = jQuery.parseJSON(results[0].data.data);
        $scope.country = jQuery.parseJSON(results[1].data.data);
        $scope.addresses = jQuery.parseJSON(results[3].data);
    }).then(function (result) {
         //do something here
    }) ;

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 comparison between actual pixels and text size in Internet Explorer?

Can you determine the actual font size in pixels corresponding to the following text size options in Internet Explorer? Largest Larger Medium Smaller Smallest In a web development project, I am looking to achieve a similar functionality to adjust the te ...

Explore the option of selecting linked data using AJAX and PHP

I'm attempting to automatically populate the Material Description field based on the Material Number selection. Both values are stored in the same SQL table. So, when I select a Material, the Material Description should auto-populate. The fields in t ...

Should I specify each protected route in the middleware file in the matcher for NextJs 14?

Below is the middleware file I've implemented: import { NextResponse } from "next/server"; import { NextRequest } from "next/server"; import { getApiAuth } from "./app/middleware/api/auth"; const validateApi = (req: Requ ...

Adjust the navigation text and logo color as you scroll on the page

I am new to HTML and CSS and I am working on a website with PagePiling.js scrolling feature. I want to change the color of my logo image and navigation text dynamically as I scroll to the next section. Specifically, I only want the part of the logo and tex ...

Implement jquery styling to ajax response

Incorporating a jquery carousel to showcase images within a dynamically updated list has proven fruitful initially. However, once the content within the carousel container is replaced via ajax, all formatting seems to vanish. The root cause of this issue ...

What is the correct way to utilize the Vuex mutation payload object effectively?

I have two input fields where I can enter a value to search for either the name of a company or the location. The search functionality works when only one argument is provided in the foundJobs mutation and action. However, when the payload contains an obje ...

Guidelines for updating values automatically from a database

Currently working on an MVC project and aiming to have the web page update automatically upon loading. For instance, if web page 1 is for adding companies to a database and web page 2 is for deleting them, once web page 2 loads, I want a select box with c ...

What exactly does <T> signify within the realm of dynamic forms?

Currently, I am experimenting with the Angular2 cookbook instructions for Dynamic Forms. The instructions mention: export class QuestionBase<T>{ value: T, ... I am confused about the purpose of the "<T>" in both instances. Do you have any ins ...

Enhance Your HTML Skills: Amplifying Table Display with Images

Recently, I utilized HTML to design a table. The Table Facts : In the first row, I included an appealing image. The second row contains several pieces of content. In continuation, I added a third row. The contents in this row are extensive, resulting i ...

I am facing an issue where my Javascript hide and show function is not working properly when clicked. Despite not giving

I am currently working on a Javascript onClick function to toggle the visibility of content in a lengthy table. I initially set part of the table's class to display: "none" and added a button to show the hidden content when clicked. However, nothing i ...

Tips for looping through multiple states within a single table

I need help with combining data from two different states, campaigns and stats, into a single table. The campaigns state includes sr no, campaign id, campaign name, and campaign status, while the stats state includes reach, sent, delivered, views, clicks ...

What is the best way to style MUI's Button component with a link to appear like a standard button?

I have a Button that allows users to download a file with a specific filename. Here is the code I used: <Button color='primary' href=`/apiproxy/objects/${id}/subobjects` LinkComponent={React.forwardRef((props, ref) => <Link {...pro ...

What is causing the delay in the execution of file_get_contents function?

When I send an AJAX POST request to a PHP script on my server, which then makes a GET request to a PHP script on an external server to check the contents of a text file, it is taking an unusually long time to return a result. Why might this be happening? ...

Submitting feedback using ajax and jquery

I need help figuring out how to display the posted comment under all existing comments, similar to Facebook's setup. Here is the code snippet I currently have: // Intercepting the submit event $('#CommentAddForm').submit(function() { ...

creating a function within an object that allows for chaining

My goal is to create a chainable object, but I am struggling to implement this in a function. This is the functionality I desire: $donate.ga('testing').go(value); The code for my object currently appears as follows: var $donate = { ga: fu ...

HTML - Transforming JSON data into a table

I'm having trouble converting JSON data into a table format. Although everything seems to be in order, I am unable to view the values on my table. Here is the code I am using to convert JSON to a table: $(function() { var my_data = &ap ...

Tips for organizing the outcome of a seamless web scraping operation with Apify and Puppeteer

Extracting data from a table on the designated URL using Apify and Puppeteer is my current goal: https://en.wikipedia.org/wiki/List_of_hedge_funds The desired outcome should be an array of objects. Each element in the array must represent a <tr> ro ...

What is the best method for automating the transfer of data from a database to the user interface of a website using html and javascript?

As a volunteer coordinator for a non-profit organization, I have some basic experience working with Python. I am willing to dedicate fewer than 8 hours of learning time to my current project in order to automate certain tasks (or else I will do them manual ...

What strategies are typically employed to prevent falling into the callback hell trap when working with error-back asynchronous functions in Node.JS?

As a new Node user, I've been practicing pure Node scripting without relying on third-party npm packages. However, I quickly ran into the issue of my code becoming nested with callbacks inside callbacks, making it difficult to follow. This can lead to ...

Encountering an unexpected end of input error while making an API call using the fetch()

I'm looking to transition an API call from PHP to Javascript for learning purposes. Unfortunately, I can't make any changes on the API side as it's an external source. When attempting to use fetch() due to cross-origin restrictions, my scrip ...