"Mastering the art of linking AJAX calls in Angular

I need to make 2 AJAX calls, with the second call dependent on the result of the first one. Currently, I am handling it in this way:

Service.getA(car).then(function(carInfo) {
    if (carInfo.success) {
        Service.getB(carInfo.number).then(function(holderInfo) {
            console.log(holderInfo);
        });
    }
});

Service:

getA: function(car) {
    return Server.execute({
        method: 'GET',
        url: 'a/a',
        params: {
            car: car
        },
    }).then(function (carInfo) {
        return carInfo;
    });
},

The getB method is similar - just a different URL and parameters. I am new to Angular and would like to refactor this code using promises and defers (as Google suggests that the code will be more elegant). How can I achieve that?

Answer №1

Your approach to chaining ajax calls is common, but there are ways to simplify it for better readability:

  Service.getA(car).then(function(carInfo) {
     Service.getB(carInfo.number).then(function(holderInfo) {
        console.log(holderInfo);
     });
  });

To handle errors more effectively, consider having your server return a Bad Request 400 status and chain the .error() callback instead of checking for success based on the success property.

Regarding Cerbrus' observation, using $q.all([promise1, promise2]) will execute promises in parallel rather than sequentially dependent on each other.

In your getA method, simply return the promise like this:

 getA: function(car) {
    return Server.execute({
       method: 'GET',
       url: 'a/a',
       params: {
           car: car
       },
    });
  }

If you need to include additional callbacks within the service, you can structure it like so:

 getA: function(car) {
    return Server.execute({
        method: 'GET',
        url: 'a/a',
        params: {
            car: car
        },
    }).then(function (carInfo) {
        //handle success

    }, function () {
        //handle error
    });
},

Answer №2

After comparing the two and noting that they are almost identical except for the URL and parameters, my recommendation would be to use the following function:

fetchData : function(apiURL, dataParams) {
    return Backend.execute({
        method: 'GET',
        url: apiURL,
        params: dataParams,
    });
},

Usage example:

DataService.fetchData('example/api', requestData).then(function(responseData) {
    if (responseData.success) {
        DataService.fetchData('another/api', responseData.id).then(function(finalData) {
            console.log(finalData);
        });
    }
});

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 are the key principles of designing web and native mobile applications using React.js architecture?

I am intrigued by the idea of incorporating React.js for server-side rendering into my web service. However, I am facing a challenge when trying to transition from my current web service built with Express.js. At present, my web service caters to two platf ...

Problem encountered when Next.js and CSRF token interact on the server

I've integrated the next-csrf library (https://github.com/j0lv3r4/next-csrf) into my next.js app to safeguard api routes. Despite following the documentation, I'm encountering a 500 error with the following message: {"message":"Si ...

Issue with TinyMCE Editor: Inoperative

<script type="text/javascript" src="<your installation path>/tinymce/tinymce.min.js"></script> <script type="text/javascript"> tinymce.init({ selector: "textarea", theme: "modern", plugins: [ "advlist autolink li ...

What is the best way to access a JSON Array in php without using any specified keys?

I'm dealing with a JSON object created in JavaScript and passed to PHP via AJAX. The issue I'm facing is that I can't figure out how to assign keys to each JSON object within the JSON array. Here's an example of how the JSON array looks ...

The Heroku application is experiencing functionality issues on mobile Safari

After developing a web application using the MEAN stack (Mongo, Express, Angular, Node) and deploying it on Heroku, I noticed some discrepancies between how it runs on different platforms. While Chrome on my computer seems to handle the app well, mobile Sa ...

JavaScript - What is the best way to add the same object value into an array?

After spending a few hours trying to figure out how to manage JSON data structured like this: [ { "value": "Osteonecrosis", "Diagnosis_Code": "DIAG002", "NamaCategory": "Primary Category", "FK_Diagnosis_Content_ID": 2 }, { "value ...

"Troubleshooting: Unable to Trigger jQuery Click Event Using Class Selector

I have two separate lists with different classes, <li><a href='#' class="cls1" name="X">blah</a></li> <!-- Click to load a cls2 item --> <li><a href='#' class="cls1" name="Y">blah</a>< ...

The minimum and maximum limits of the Ionic datepicker do not function properly when selecting the month and day

Recently, I have been experimenting with the Ionic 2 datepicker. While the datepicker itself works perfectly fine, I've run into some issues when trying to set the min and max properties. <ion-datetime displayFormat="DD-MM-YYYY" [min]="event.date ...

Is there a way for me to instruct jQuery to revert an element back to its initial value, prior to any dynamic alterations?

My question is regarding changing the content of a div using the `html()` method in JavaScript. I am currently working on implementing a "cancel" button and would like to revert the content back to its original value without having to completely reset it w ...

transferring information between two ajax calls upon completion of the first ajax request

Attempting to pass data to jvectormap from an ajax call, using a when function to ensure the code runs after the ajax call has finished loading. The issue I'm facing is that the map appears empty and I encounter an error. Uncaught ReferenceError: ...

What is the proper way to utilize the `replace` property in directive definitions?

When referencing the document at http://docs.angularjs.org/guide/directive, it explains the replace configuration for directives: template - replaces the current element with the specified HTML content. During this replacement, all attributes/classes fr ...

What is the reason for Cloud Firestore's realtime database fetching all items?

Currently, I am developing a project with vuejs and I am facing an issue where I need to fetch only the last created item from Firestore's realtime database. However, when I execute the following code snippet, it retrieves all items from the database ...

Interactive auto-updating view

After setting up a small demo application to refresh partial views via jQuery/Ajax, I came across several examples that refreshed the partial view from the main view. However, I couldn't find one where it refreshes from the view itself. Below is the ...

What is the method for retrieving the fixed information?

I am currently working on a project that involves creating a course-rating API. We have been given a completed angular application to work with, and our task is to set up the routes without making any changes to the Angular app. One of the initial tasks a ...

Enable automatic scrolling when a button on the previous page has been clicked

Imagine there are two buttons (Button 1 and Button 2) on a webpage (Page A). Clicking on either button will take you to the same external page (Page B). How can we ensure that Button 1 takes you to the top of Page B, while Button 2 automatically scrolls do ...

Issue encountered: Unable to fetch username and password from request

Currently, I am developing a login and registration system. However, when I input the correct details in my register Post method, the request remains pending and I cannot identify the error. The specific error message it presents is data and salt arguments ...

Exploring the capabilities of jest-next-dynamic through dynamic imports in Jest testing

Currently, I am in the process of testing dynamic imports in Next.js version 10.2.3. To achieve this, I decided to utilize the jest-next-dynamic library to prevent any potential errors from occurring. However, during my testing, I encountered a TypeError ...

The JQuery pagination feature fails to function properly once an AJAX load is initiated

I am using jspages.js to implement pagination with jQuery. Everything works fine when the page is initially loaded. However, I encounter an error when the content for pagination is loaded after an ajax call. The plugin does not seem to work as expected. ...

Utilizing AJAX to send a parameter to PHP for processing

I am facing an issue with a script that is supposed to send data to a PHP file when a user clicks on an element, but unfortunately, it's not functioning correctly. Below is the jQuery code: jQuery( document ).ready(function( $ ) { $('.rve_b ...

Ajax is functioning properly on Internet Explorer and Safari, however it is not functioning on Firefox, Chrome, or Opera

I am attempting to retrieve modal data from an HTML page using jQuery Ajax. It seems to be functioning properly in Safari and IE 6, however I'm encountering issues in Firefox, Chrome, and Opera. Any suggestions on how to resolve this? You can find my ...