Linking asynchronous AJAX requests using Angularjs

Currently in my AngularJS project, I have created a service with multiple functions that return promises.

The AJAX Service I've Created:

angular.module('yoApp')
    .factory('serviceAjax', function serviceAjax($http) {
      return{
      
        configDataSets:function(path){

          return $http.get(path);

        },
        fileList: function(site_url,dataSet,varName,region,date){
          return $http.get(site_url + "mwf/" + dataSet + "/" +varName + "/" + region + "/" + date + "/filelist/");
        },
        config: function(site_url,dataSet){
          return $http.get(site_url + "mwf/" + dataSet + "/config/");
        },

      }});

Code in the Controller:

I've already implemented something similar to this, but considering potential chained requests, I believe there might be a more efficient way to handle this:

serviceAjax.config(site_url,$scope.dataset).then function(data){
          $scope.config=data.data;
serviceAjax.configDataSets("images/configDatasets.json").then(function(data){

          $scope.configDatasets = data.data;
 
});
});

In order to improve the process, I want to first call config in my controller and then proceed to configDataSets, waiting for each operation to finish. I have explored options like $q and deferred, but struggling to find the best approach. Any guidance would be highly appreciated!

Answer №1

To handle promises, you can simply utilize the .then method that is provided:

serviceAjax.config(function(response) {
     // extract data from the first API call
     ...
}).then(function() {
     return serviceAjax.configDataSets("images/configDatasets.json");
}).then(function(response) {
     // utilize data from the second API call
     ...
});

You may also want to consider using $resource over $http if your HTTP service aligns with RESTful conventions.

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

Add some flair to your list by animating the text within it

My goal is to add animation to the text within the list. Below is the code snippet: <div id="about" class="row section"> <div class="col-sm-8"> <h2 style="color:black;">About me!</h2> <ul> <li > ...

Is it possible to refresh user data in PHP without reloading the page using Ajax technology?

I implemented a user information update feature in PHP, but I encountered an issue where the form is embedded within one of the tabs on my website:https://i.sstatic.net/nFR9X.png After filling out the form and submitting it, the page refreshes and redirec ...

The dual-file upload feature of the jQuery ajaxForm plugin

After extensive searching online, I have yet to find an answer to my problem. The issue at hand is that when using the ajaxForm malsup plugin, it submits my files twice. HTML: <form id="gallery" enctype="multipart/form-data" action="/upload-gallery.p ...

Is it possible to generate distance between 2 elements without utilizing padding or margin?

In my React Native project, I'm currently working with 2 inline buttons - the search and add buttons: https://i.stack.imgur.com/tKZrf.png I'm looking to add some spacing between these buttons without impacting their alignment with the left and ...

How can we transform words with double "OO" in a paragraph into green squares using React? For instance, changing "clooney" to "cl[green square]ey"

import React, { Component } from 'react'; class App extends Component { constructor() { super(); this.state = { modifiedPar: "", newPar: "modified paragraph will be displayed here"}; } greenSquareMaker = word = ...

JQuery's .ajax function often triggers the success callback before the page it is calling

Below is the code I am currently working with: <script type="text/javascript"> $(function(){ $("#AddMaps").submit(function(){ var $form = $('#AddMaps'); $.ajax({ type: 'POST&a ...

Is there a way for me to upload a file after my form has been submitted, rather than immediately after it is selected?

Currently, the file is being uploaded to a folder immediately after it is selected from the window that pops up. However, I want the file to be only selected at first and then uploaded when the form is actually submitted. Additionally, I need to retain the ...

Is it possible to improve the cleanliness of a dynamic button in Jquery?

I've just finished creating a dynamic button on the screen as per my boss's request. When this button is clicked, it triggers an email window for feedback submission. My aim is to streamline this script so that I can avoid digging into ASP marku ...

Create a new array by applying a filtering function to the provided data in JavaScript using React

I am a beginner in the world of React. I have an object containing an array (Map) as follows: "POSSIBLE_UPDATE_OPTIONS": { "Process": ["confirm"], "Confirmed": [ "Process", ...

Enabling Context Isolation in Electron.js and Next.js with Nextron: A Step-by-Step Guide

I've been working on a desktop application using Nextron (Electron.js + Next.js). Attempting to activate context isolation from BrowserWindow parameters, I have utilized the following code: contextIsolation: true However, it seems that this doesn&ap ...

Display results in a Web application using Google Apps Script

function doGet() { return HtmlService.createHtmlOutputFromFile("vi"); // var output = HtmlService.createHtmlOutput('<b>Hello, world!</b>'); } function doPost() { return HtmlService.createHtmlOutputFromFile("vi"); // var out ...

JSON isn't transmitting any information

Having an issue with Json that's puzzling me. I'm using ajax to call a Controller method that takes a string as input and returns a List of my defined class. The json call is triggered by a dropdown menu change, loading the corresponding fields ...

Inserting blocks of text into a MySQL database

I'm hoping to insert text segments into a MySQL database. Below is an excerpt of my HTML code: <div class="margins3"> <h1>Meal Plan...</h1> <div id='results-container'> <div class='LeanMuscle ...

When attempting to use Ajax, the operation fails; however, if I directly access the URL,

When using firebug, I attempted to make the following AJAX call: var rootUrl = 'http://172.24.105.22:8080/geoserver/Chennai_Sub/ows'; var defaultParameters = { service: 'WFS', version: '1.0.0', request: 'Get ...

The React setState function isn't updating the state as expected when used within the useEffect hook

I'm new to using hooks and I'm facing an issue with setState when trying to update data received from an API. Despite logging the response data successfully, it seems that the state does not update as expected. My useEffect function is set to run ...

Troubleshooting: jQuery script encountering issues with loading Bodymovin JSON files

The animations for the slider and shuffle lottie are designed to go from 0 to 100 and then back to 0 when toggled, similar to the box animation. However, it appears that the slider animation disappears in the final frame while the shuffle animation appear ...

The cube mesh is failing to render inside the designated div

I created a Torus and Cube Mesh in my scene, but I want the cube to be positioned at the bottom right corner of the screen. Here's what I tried: <div style="position: absolute; bottom: 0px; right:0px; width: 100px; text-align: center; "> & ...

What is the best way to organize a table with multiple state variables using nested loops?

What is the best way to display multiple variables in a table using a loop, such as i,j,k? this.state = { materials: ['m1', 'm2'], quantity: ['2', '4'], unitPrice : ['12&apo ...

Is there a way to showcase the present weather conditions using simpleweather.js in plain text format?

I have integrated the weather.js library into my HTML file by adding the necessary imports: <script src="js/current.js"></script> <script src="js/sugar.min.js"></script> <script src="js/weather.js"></script> <script ...

Implementing nested popup windows using Bootstrap

I am facing an issue with my two-page sign-in and sign-up setup in the header of my angular2 project. On the sign-up page, I have a link that should redirect to the sign-in page when clicked, but I am struggling to make it work. Can someone provide guidanc ...