What is the best way to utilize the outcome of the initial API request when making a second API call in AngularJS

Looking to utilize the response of a first API call in a second API call. The situation is such that I need to fetch data from the first API and use it in the second API call. I believe a synchronous API call would be necessary. While attempting to implement this functionality, I encountered an issue where function2 was being executed before function1. It's crucial that function2 relies on result1, which can only be obtained after calling function1. How should I proceed?

$scope.function1 = function(){
        var deferred= $q.defer();    
        $http.post(api1, data1)
        .success(function(response, status) {
          if (response.error == 0) {
            console.log(response.result);          
               $scope.result1=response.result;      
          }           
        }) ;    
        deferred.resolve('Success') ; 
        return deferred.promise;       
    };
    var promise =  $scope.addDefaultValue();
    promise.then(function(){
      $scope.function2();
    });

     $scope.function2=function(){
        var deferred = $q.defer();

        $http.post(api2,result1)
        .success(function(response, status){
          if(response.error == 0){

          }
        });
      deferred.resolve('Success') ;
      return deferred.promise;
    }

Answer №1

To implement the promise chain pattern, simply use the .then method on the promise object.

Avoid creating unnecessary promises using $q, as the $http methods already return a promise object when initiating an ajax request.

Example:


$scope.function1 = function() {
  return $http.post(api1, data1)
    .then(function(d) {
      var response = d.data;
      if (response.error == 0) {
        console.log(response.result);
        $scope.result1 = response.result;
      }
      return response;
    });
};

$scope.function1().then(function(data) {
  $scope.function2();
}, function(error) {

});

Answer №2

Trying to make $http requests synchronous is not the purpose of using "deferred". Deferred is specifically meant to convert functions that are not promise-capable into ones that are promise-capable. Since $http functions already return promise objects, you do not need to utilize deferred in this scenario.

$http.post(api, data1).then(function (response) {
  $scope.result1 = response.data.result;
  // Return statement here is crucial
  // for continued chaining with .then
  return $http.post(api2, response.data.result);
}).then(function (response) {
  // This block receives response from api2
  $scope.result2 = response.data.result;
  console.log(response.data);
}).catch(function (error) {
  // Errors from either API calls can be handled here
  // Second API call will not be executed if the first one fails
  console.log(error);
});

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

modifying input field with radio button selection in Jquery

Is there a way to set the input field to have a default value and then change it, or disable it with a different value? $("#tax").value(19).prop("disabled",false); $("#tax").value(0).prop("disabled",true); <script src="https://ajax.googleapis.com/aj ...

"Troubleshooting a case where mongoDB's updateOne function is

I am in the process of removing certain references to objects within different sections (section1, section2, section3, others) in each file. Sample Document: { "_id": "64a3268474aa29e72b40c521", "name": "Test", ...

Executing a function on each page within the head tag in Nuxt.js

I successfully made my function accessible by using the plugin attribute in the nuxt.config.js file, allowing me to call the function under mounted on every page. I am looking for a more efficient way to run this function within the head tag and have it b ...

Filtering Quantity Based on Specific Attribute in ReactJs

I want to implement a quantity filter that can be based on color, size, or both. For instance, when I select the red color, it should display the total quantity of red items available. However, if I choose both the color red and size small, it should show ...

Tips for preventing the inner surface from appearing transparent in WebGL

I am working with the code snippet provided below. The issue I am currently facing is that one side of the partial sphere is non-transparent, while the other side remains transparent. How should I modify the code to make both sides non-transparent? Thank y ...

What is the best way to ensure that my image completely occupies the div?

I am facing a challenge in creating a hero image that would completely fill the div on my webpage. Despite setting the width and height to 100%, the image seems to only occupy half of the space. Check out the CSS and HTML code snippet here. div.hero{ ...

The back-to-top button guides users back to their last visited page

I'm excited to explore AngularJS and I want to add two "return to top" buttons on different pages. Here's what I have so far: Page 1: <h1 id = "top"> .......... <a href="#top" target = "_self">Return to Top</a> Page ...

Obtain the sender using an href JavaScript code

Is there a way to retrieve the tag that called a javascript function if the anchor has a href tag of javascript:someFunc()? I know that in the onclick attribute, you can pass this, but when called from the href tag, this references the DOMWindow. Unfortu ...

Utilizing NodeJS and AngularJS: Retrieve and store file using $http.get() method

Currently, I am in the process of developing an Electron application using NodeJS and AngularJS. The main goal of this app is to download mp3 files from a web service and save them to a specific folder on the user's device. In order to achieve this fu ...

Preventing special characters, numbers, and spaces from being used as the first character in a word in HTML with regular expressions

Is there a way to restrict users from inputting special characters, numbers, and spaces only in the first place of a word using regex in HTML? <label><span>Current Carrier</span></label> <input name='Current Carrier' t ...

The JSON at position 0 threw a curveball with an unexpected token "u

Whenever I attempt to convert a string to an object, I encounter an error: Unexpected token u in JSON at position 0 Service setUser : function(aUser){ //save User localStorage.setItem('User', JSON.stringify(aUser)); }, getUser ...

Enhancing the structure and authentication of license plates

I'm having trouble figuring out how to apply Javascript to the text area. Can you advise on whether it's best to use onfocus, onblur, or onclick? Here is the code for the text area: <input type="text" name="c_Kenteken" id="invoerKenteken" cl ...

How can you utilize Javascript to retrieve an element by its inner text within the HTML tags?

As a novice, I have been struggling to find the solution to my question even after extensive searching. In the scenario at hand, I am specifically interested in locating the following element: <a href="bla" onclick="dah">some text here</a> I ...

The background on my modal remains unchanged

I have integrated a modal using Iframe for user login/registration on my website. Here is the HTML code: <div class="modal" id="ays-popin-connexion" aria-hidden="true"> <div class="modal-body" aria-hidden="true"> <iframe src=" ...

Connect various models together, or create synchronized computed properties

At times, the model abstraction may fall short, leading to the necessity of synchronizing two different models. For instance, I have two lists linked by an angular sortable, which requires a model structure like this: left = [{name:"one"}, {name:"two"}]; ...

Is there a way to verify the presence of data returned by an API?

I am trying to implement a system in my Index.vue where I need to check if my API request returns any data from the fetchData function. Once the data is fetched, I want to return either a boolean value or something else to my Index.vue. Additionally, I wou ...

jQuery problem causes page to scroll when button is clicked

Is there a way to smoothly scroll to the second section of the page when a button is clicked using jQuery? $('.home_scroll_btn a').on('click', function(){ var scrollPosition = $('#intro-home').offset().top; $( ...

Can you effectively leverage a prop interface in React Typescript by combining it with another prop?

Essentially, I am looking to create a dynamic connection between the line injectComponentProps: object and the prop interface of the injectComponent. For example, it is currently set as injectComponentProps: InjectedComponentProps, but I want this associat ...

Efficiently configuring an Array with Wordpress REST API in JavaScript

Here's a two-part question: 1) My goal is to fetch elements from WordPress' REST API and store them in an array called map_locations. The first part of the function involving $.ajax works as intended, showing data when I log it. However, the lat ...

Display error messages upon submitting the form

I am currently working on an Angular 6 Form with validation. My main goal is to display error messages only after the form has been submitted. It is crucial that these messages remain constant while the user types in the input field. For instance, if a use ...