What's the best way to link two http requests in AngularJS?

Currently, I am facing the challenge of chaining two http calls together. The first call retrieves a set of records, and then I need to fetch finance data for each individual record.

flightRecordService.query().$promise.then(function (flightRecords) {
  $scope.flightRecords = flightRecords;
  for (var i = 0; i < $scope.flightRecords.length; i++) {
    $scope.flightRecords[i].financeDocument =
      financeDocumentService
      .isReferencedDocumentIdCompensated({
        id: $scope.flightRecords[i].id
      }).$promise.then(
        function (data) {
          return ({
            'isCompensated': data.headers['compensated']
          });

        }
      );
    console.log($scope.flightRecords);
  }
});

This section showcases the FlightRecord object:

$$hashKey: "object:27"
aircraft: {id: 100, registration: "LV-OEE", model: "152", status: "ACTIVE", brand: "Cessna", …}
amountOfHours: 1
canceled: false
closed: false
crew: [Object] (1)
destiny: null
endFlight: "2017-01-06T20:54:05.296"
financeDocument: d
  --> $$state: {status: 1, value: {isCompensated: "false"}}
  --> d prototipo
id: 100
landings: 0
nature: "LDI"
opened: true
origin: null
purpose: "VP"
startFlight: "2017-01-06T19:44:05.296"
status: "OPENED"
type: "ENT"

I have noticed that the structure of the financeDocument object is not as expected. I require it to be in the following format:

...
endFlight: "2017-01-06T20:54:05.296"
financeDocument: { isCompensated: "false" }
id: 100
...

What modifications should be made to achieve this desired structure?

Thank you in advance!

Answer №1

To update each entry in the "flight record" after fetching additional details, you should make use of the modify function. Additionally, consider utilizing $q.all to notify the caller once the operation is finished.

const promise = flightRecordService.query().$promise.then(flightRecords => {
  return $q.all(flightRecords.map(flightRecord => {
    return financeDocumentService.isReferencedDocumentIdCompensated({
      id: flightRecord.id
    }).$promise.then(data => Object.assign(flightRecord, {
      isCompensated: data.headers.compensated
    }))
  }))
})

promise.then(flightRecords => {
  $scope.flightRecords = flightRecords
})

Answer №2

Is there a reason why we shouldn't just set it on the original object?

After retrieving flight records using flightRecordService.query(), the code sets those records to $scope.flightRecords and then iterates through each record. Within this iteration, a function is called on each record to check if the referenced document ID is compensated. If so, the financeDocument property on the record is updated accordingly.

Answer №3

When attempting to set the financeDocument property with a Promise synchronously, it is important to ensure that the variable is set within the success callback of the promise.

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 methods can a Discord Bot use to respond with specific messages to individual users?

Hey there! I'm dipping my toes into the world of coding and thought it would be fun to create a Discord bot that gives different responses each time it's mentioned. Just so you know, I'm working with Discord.js version 13 for this project. ...

How can I manipulate the JSON property, an array of objects, within a React component?

As a newcomer to react development, I am facing an issue while trying to display a product page with its summary using JSON data containing arrays of objects. Upon attempting to use .map function, I encountered an error stating that the prop is undefined. ...

"JS Kyle: Utilizing JWT for Signing and Encrypting Data

I am currently using jose for signing and encrypting JWTs, but I am facing an issue when trying to sign and then encrypt the entire JWT. When it comes to signing my JWT, I utilize the following function: const secretKey = process.env.JWT_SECRET; const key ...

What is the best way to change the order of rows and columns in

Is there a way to rotate a table using jQuery? Maybe with a function or some other method? For instance, if I have a table structured like this: <table> <tr> <th></th> <th></th> <th>&l ...

The current date object in JavaScript will only display the year or a combination of the month and

$scope.articles = [ { link: "http://google.com", source: "Google", title: "hello", "date": new Date(2008, 4, 15) }, ]; <tbody> <tr ng-repeat = "article in articles | orderBy:sortType:sortReverse | filter:searchArticle ...

Guide to parsing JSON with Java

Transferring a JSON string (inputJson) to my Java code (PPProgramAddView) on the server side. PPProgramAddView: inputJson: [{"ppl_row":0,"ppl_time":"07:00","ppat_id":"Mw==","ppa_id":"MTI=&quo ...

Is it unnecessary to mention both JavaScript and AJAX together?

During a recent conversation I had, someone mentioned that it is inaccurate to state that since Ajax is JavaScript. The scenario was: "How can I perform an action on a webpage without requiring a page refresh?" My response: "Utilize JavaScript along wi ...

Utilizing i18next-express-middleware for seamless language switching based on user input

As a newcomer to node.js, I am looking to internationalize my application. To kickstart this process, I have utilized the template available on i18next-express-middleware github in conjunction with resources from the i18next website. My goal is to enable u ...

Synchronize the completion of multiple promises in ExpressJs before sending a response

My POST API contains some logic that needs to wait for all promises to finish before sending the response. However, I'm facing an issue with making my server wait using await Promise.all(tasks); I've tried various approaches and even used librar ...

transforming information into hierarchical JSON format using C#

I am working with a data table that has the following structure: Table structure of given data. The table consists of four columns namely Id, Name, Salary, and RefId. In the RefId column, we store the ID of the parent object. Below is the modal class for ...

Is it possible to prevent certain values from being converted into numeric when using json_encode?

Whenever I utilize PHP (5.4/5.5) along with the json_encode() function, I encounter some difficulties when implementing the JSON_NUMERIC_CHECK parameter. It's a live system, so removing the option is not an ideal solution as it would disrupt the respo ...

Open the link and input the text into the text box?

Suppose I have the following JavaScript code: <script language="javascript" type="text/javascript"> function addText() { var newText = document.myForm.inputText.value; document.myForm.description.value += newText; } </script> I want t ...

Leverage the power of JSON values by incorporating them directly into HTML tags

My JSON file is generating the following styles: { "h1" : { "font-family" : "Lato", "font-size" : "24px", "line-height" : "28px", "font-weight" : 600, "colorId" : 3, "margin-bottom" : "10px", "margin-top" : "20px" }, "h2" : { ...

How should post comments be stored effectively in Firebase?

Currently, I am in the process of developing an app utilizing Firebase with a classic blog format as its foundation. This application will consist of properties (similar to posts), users, and comments associated with each property. I am deliberating on w ...

Exploring the Node.js view object within a function and delving into the reasons why a property of

As a beginner in programming, I am seeking tips on how to effectively learn node.js. Currently, I am utilizing the "Learning Behavior Driven Development with JavaScript" book for my learning journey. I would greatly appreciate any advice on how to view ob ...

Variations in the module pattern in JavaScript

Can someone help me understand the differences in these methods of creating a javascript "module"? I'm just looking for some clarification. A) var foo = function() { var bar = function() { console.log('test'); }; retur ...

Trouble with uploading images through multer is causing issues

When setting up multer, I followed this configuration let multer = require('multer'); let apiRoutes = express.Router(); let UPLOAD_PATH = '../uploads'; let storage = multer.diskStorage({ destination: (req, file, cb) => { ...

Transferring data from CSV or JSON formats into MongoDB

What is the most efficient way to import 5MB of raw data: converting it into CSV first and then importing to MongoDB, or importing it as JSON directly to MongoDB? ...

What is the process for extracting information from JSON data that is not in

Attempting to extract data from a local .json file by utilizing StreamReader and Json.NET. The json content and code snippet are as follows: Contents of .json file: {"rate":50,"information":{"height":70,"ssn":43,"name":"andrew"}} using (v ...

Is there a term similar to "Rise above the Rest" in the world of Web Development?

Hey, I've encountered a new issue right now. Currently, I have two elements that are fixed to the top and bottom of the page. However, the elements in between them are overlapping the top element. Even though I tried keeping both elements fixed, th ...