displaying information simultaneously in AngularJS

Being a complete novice in Angular, I am struggling to find the best solution to solve this particular issue. Let's say we have two users, 'A' and 'B', who owe money to each other.

User 'A' has 5 transactions and needs to pay $5000 to user 'B'. On the other hand, user 'B' has 50000 transactions and owes $100000 to 'A'. The current code displays 2 transactions instead of 1, requiring mental calculations. The code snippet is as follows:

$scope.charges = {};

totalChargeUserToFactory.query({
    id: null
}).$promise.then(function (data) {
    $scope.charges.to = data;
});

totalChargeUserFromFactory.query({
    id: null
}).$promise.then(function (data) {
    $scope.charges.from = data;
});

To address this issue, I made the following changes in my code:

$scope.charges = {};

totalChargeUserToFactory.query({
    id: null
}).$promise.then(function (data) {
    $scope.charges.to = data;

    totalChargeUserFromFactory.query({
        id: null
    }).$promise.then(function (data) {
        $scope.charges.from = data;

        // Code for handling transactions between users A and B

    });
});

However, a new problem arises - with a large number of transactions, it takes time for the content to load. User A may appear quickly on screen, but there is a delay of 2 seconds before user B shows up. This does not provide a good user experience. Can you suggest any tips or modifications based on this code snippet to improve performance?

I tried searching online for solutions, but couldn't find anything satisfactory that directly addresses my issue.

Answer №1

To utilize your original design and run some code after both promises have successfully resolved, you can leverage the $q.all() method.

$scope.expenses = {};

var promise1 = getTotalExpenseFromUser.query({
    id: null
}).$promise.then(function (data) {
    $scope.expenses.to = data;
    return data;
});

var promise2 = getTotalExpenseToUser.query({
    id: null
}).$promise.then(function (data) {
    $scope.expenses.from = data;
    return data;
});

$q.all([promise1, promise2]).then(function(data) {
    // perform calculations here
})

Answer №2

To ensure that all your API calls finish before displaying any data, consider using $q.all method.

$q.all([
  getTotalChargeUserToFactory.query({
    id: null
  }),
  getTotalChargeUserFromFactory.query({
        id: null
  })
]).then(function(results) {
     $scope.charges.to = results[0];
     $scope.charges.from = results[1];
   });

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

Implementing a jQuery date selection feature with Rails 3.2.8 and AngularJS: troubleshooting date display and persistence issue

Struggling to get the rails+angularjs+jQuery datepicker trio to work in harmony. The issue arises when trying to display dates retrieved from the backend. When data is requested from the backend, it is received in JSON format like this: {"id":1,"ragione_ ...

Using Javascript and HTML5 Canvas to retrieve dimensions of selected objects

I have a canvas with an image containing colored squares. I want to be able to click on a square and retrieve its dimensions in pixels. For instance, clicking on a red square with a yellow border should return 24 X 100. I've come across some code that ...

Iterate through the array in order to showcase or output it in PHP syntax sourced from an API

[0] => Array ( [id] => 6 [name] => Digitally Imported Psy Goatrance [country] => GB [image] => Array ( [url] => https://img.dirble.com/station/6/original.png ...

How can I stop jQuery from repeatedly appending content every time I click the button?

Hey there, I have a question about calling a JSON array using jQuery. Every time I press the button, it loads the list again instead of multiplying. Here is the JSON array: [{"denumire":"Q Club"},{"denumire":"Carul cu Flori"},{"denumire":"La Rocca"}] And ...

Create a universal function similar to onbeforeunload that works seamlessly across all web browsers

Can I implement an onbeforeunload function that works on all browsers? window.onbeforeunload = function () {/**/} I need to run a script when a link on my website is clicked. Currently, I'm using an onclick event-based script, but it doesn't f ...

The Vue application is unable to expand to 100% height when using a media query

Hello everyone, I'm currently using my Vue router for multiple pages, and I'm facing an issue where setting the height of the main container to 100% within this media query is not working as expected: @media screen and (min-width: 700px) { #sig ...

What could be causing my LESS files not to compile properly in grunt?

I've successfully installed npm and ran npm init. Additionally, I've installed the following packages using npm: grunt grunt-contrib-less grunt-contrib-watch jit-grunt --save-dev My Gruntfile.js configuration looks like this: module.exports = f ...

Restricting user access to a route based on its type to enhance security and control

Currently, I have a React, Redux, and Next.js app up and running. Within my redux store, there is a user object that contains an attribute called "type". Each type of user has its own set of "routes" they are allowed to access. I am looking for the most e ...

A guide on integrating a stacked bar chart from ApexCharts into a modal or v-dialog component

I'm facing a minor issue with vue-apexcharts while attempting to showcase some data in a stacked bar chart. Here is the simple component I have created: <template> <div v-if="this.loaded"> <apexchart w ...

Performing a POST request using XMLHttpRequest with parameters in an asp.net environment

I am working on utilizing a javascript XMLHttpRequest object to send a post request to my action method. Here is my current setup: xmlhttp.open('POST', '../Employees1/HandleFileUpload', true); My action method does not currently take ...

How can you apply a class to a different element by hovering over one element?

Is there a way to darken the rest of the page when a user hovers over the menu bar on my website? I've been playing around with jQuery but can't seem to get it right. Any suggestions? I'm looking to add a class '.darken' to #conte ...

implementation of bug decrementation with a fadeout

For my current project, I need to implement a feature where individual elements containing a photo and their corresponding title fade out when clicked. However, the issue is that clicking on any picture fades out everything. How can I resolve this so only ...

Vue.js: Conditionally preventing form submission

Currently, I am implementing form validation using VeeValidate. Although I prefer not to rely on JavaScript for form submission, I still want to prevent users from submitting the form if there are any errors present. However, using the code snippet below s ...

Modifying the color of the initial day of an event on fullcalendar.io v5

Is there a way to change the background color of only the first day of an event, while keeping the rest of the days the default color? I came across the function eventDidMount: function (event){ }, but I'm not sure how to specifically target and cha ...

Tips for implementing a switch-case statement with variable formats that may not always be

switch (req.path) { case "/api/posts": console.log("posts"); break; case "/api/posts/tags/*": // the part * is always changing depending on user input console.log("tags"); break; case "/api/best": console.log ...

"Embedding PHP code within HTML tags, which is then embedded within

Running into an issue within a while loop... echo 'var contentString = '<div id="content" > <div id="bodyContent"> <p>' + $row[name]+ '</p> ...

What is preventing Safari and Firefox from properly handling audio data from MediaElementSource?

It appears that neither Safari nor Firefox can process audio data from a MediaElementSource with the Web Audio API. var audioContext, audioProcess, audioSource, response = document.createElement('h3'), display = document.createElement( ...

Guide on transforming Div content to json format with the use of jquery

I am trying to figure out how to call the div id "con" when the export button is clicked in my HTML code. I want it to display JSON data in the console. If anyone has any suggestions or solutions, please help! <html> <div id ="con"> < ...

Having trouble with your Bootstrap modal not opening automatically when the page loads?

I have a modal that is successfully opening with a button: <button onclick="content()" data-toggle="modal" data-target="#my_modal">Save</button> <form action="addPage.php" method="post"> <div class="modal fade" id="my_modal" tabind ...

Utilize the id in AngularJS to bring attention to a specific row within a table

I am brand new to using angularjs. I currently have a table structured like this: HTML <table class="table table-striped" id="manageResumeTable"> <thead class="text-center text-info text-capitalize"> <th class="text-center col- ...