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

Error 500: An invalid data type was encountered in an express.js node.js environment

Currently, I am in the process of developing an Authentication page using a combination of node.js, express.js, and mysql2. The user ID and password entered on the webpage are then passed through app.post('/login',...). However, upon submitting t ...

Using JavaScript: Retrieve the URL from a JSON file and run it in the background

I am looking to make a JSON request using jQuery: $.getJSON('http://example.com/file.php', function(data) { //data }); An example of the JSON output: { "url":"http://example.com/execute.php" } Next, I want to silently execute the URL on th ...

Storing Images in MongoDB with the MEAN Stack: A Guide using Node.js, Express.js, and Angular 6

I am currently working on developing a MEAN Shop Application, and I have encountered an error while attempting to store the product image in MongoDB. typeError: cannot read the property 'productimage' of undefined Below is the route function fo ...

Updating Angular.js scope after a variable has been modified

On my website, I have implemented a search bar that communicates with a controller receiving JSON responses from the server. The response is stored in a global variable called assetResult. It works as expected initially; however, subsequent searches do no ...

Make sure to properly check the size of the image before uploading it in express js

Below is the code I have written to verify if an image's size and width meet the specified criteria: im.identify(req.files.image,function (err,features) { //console.log(features); if(features.width<1000 ...

Tips for including a line within a circular canvas

My progress bar crafted with css, javascript and html looks great (left image). However, I'm facing a challenge in adding white color dividers to enhance the appearance of the progress bar as shown in the image on the right. Despite my various attemp ...

Can you explain the distinction between document.body.ononline and navigator.onLine?

Can you explain the distinction between document.body.ononline and navigator.onLine? Do they utilize the same JavaScript API for checking network connectivity status (online/offline)? I have searched on Google but couldn't find a definitive answer. If ...

Dynamic inheritance in Node.js based on the version being used

Why does the code provided only function correctly in Node.js versions 5.x and 6.x, but not in versions 4.x and older? Is there a way to modify the code so that it can work across Node.js versions 0.10.x - 6.x? 'use strict'; var util = require ...

Creating dynamic height based on width using JavaScript

I'm trying to make a rectangle responsive based on the width of the window. This is my current logic: aspectRatio = 16 / 9 win = { width: window.innerWidth, height: window.innerHeight, } get browser() { const width = this.win.width - 250 ...

Issue in Jquery: Unable to load the corresponding pages when toggling the checkbox on and off

I am facing an issue with a checkbox and calling different php pages based on the status of the checkbox. Currently, the code works only for checked checkboxes. I'm not sure why it's not working for unchecked checkboxes as well. <script type ...

Using Node.js to store all data as null in SQL database

I am currently working on developing an API using Node.js with Express and MySQL. I am facing an issue in the POST method where all values are being stored as 0 in MySQL, as shown below: 1 0 0.00 0000-00-00 0 (the 1 represents the autoincremented ID) To ...

Struggling to find the width of an SVG text box or add line breaks after a specific number of characters?

I am currently working on creating an SVG text box using the amazing Raphael library. The content inside this text box comes from a dynamic string that is extracted from an XML document. There are times when this string turns out to be longer than the can ...

Instructions on how to insert a new row into Datatables following the successful submission of a form via AJAX请求

Could someone please provide guidance on how to insert a new row into an existing datatable after a successful AJAX request? Here is the code I am currently using: $(document).ready(()=>{ $.ajax({ url: 'http://localhost:3000/api/post/getUserDat ...

Is there a way to incorporate additional text into option text without compromising the existing values?

One challenge I'm facing is adding additional text to the options without changing their values upon selection. Would you be able to assist me with resolving this issue? I have come across the following HTML code: <select id="q_c_0_a_0_name"> ...

All fields in the form are showing the same error message during validation

This is the HTML code: The form below consists of two fields, firstname and lastname. Validation Form <form action="" method="post"> Firstname : <input type="text" placeholder="first name" class="fname" name="fname" /> <span class= ...

Creating a custom directive for input validation in Angular

I am currently working on building a basic custom directive in AngularJS to validate if the user input is an integer or not. When the user types in an integer, I want an error message to display at the bottom that states "integers are not allowed". Do yo ...

Is extracting the title of an image from Flickr?

I have a JavaScript code that randomly pulls single images from Flickr every time the page is refreshed. Now, I want to add a feature where the title of the image is displayed when it's hovered over. However, I've been searching for a solution fo ...

Ways to retrieve the length of the parent array within a component in AngularJS

Is there a way to access the value of a property in the parent from within a component? Parent: export class Animal{ animalID ?: Array<number>; { Child: import {Component, Input} from '@angular/core'; import {Animal} from '../anim ...

Error in sending Ajax form

I have a form that is set up to send data to a server. When the form is in its regular HTML format, everything works smoothly and all data is successfully transmitted to the server without any issues. However, as soon as I switch the form to use AJAX for s ...

Encountering an issue of duplicate key error when using multiple v-for loops with various keys

I've encountered an issue while working on a Python application that utilizes Vue.js. A ticket came my way with an error message stating: [Vue warn]: Duplicate keys detected: ''. This may cause an update error. (found in Root) The pro ...