How can we refresh data obtained from a $http server call in AngularJS?

My controller is configured to load data from a server request initially, but I need to implement a refresh button that will send another request with updated parameters. The issue I'm facing is that the asynchronous nature of the request means the data is not available in time. How can I make my refresh method synchronous?

function DataController($scope, $http, $location,$filter) {

    $scope.mydata=[];
    $scope.requestUrl="";
    $scope.requestConfig =[];

    $scope.loadDatas = function () {    
        var params = {
                offsetParam: $scope.offsetParam
              };
         var config = {
                    params: params
                  };

        var url='server/loadmydata/';

        $scope.requestUrl = url;
        $scope.requestConfig = config;

        //Fetch data from server
        $http.get(url,config)
            .success( function (data,config) {
                $scope.mydata = data;
                $scope.offsetParam =$scope.offsetParam + data.length;           
            })
            .error(function(data,config){
                $scope.error = data;
            });
    };

          // Refresh fonction
          $scope.refresh = function() {

            var params = {
                        offsetParam: $scope.offsetParam,
                           };

                $scope.requestConfig = {
                            params: params
                          };
            $http({
                    method: "GET",
                    url : $scope.requestConfig,
                    params :params
                }).then(function(data) {

                        if(data && data.length>0){
                            $scope.mydata = push(data);
                            $scope.offsetParam =$scope.offsetParam + data.length;
                            }
                    });

          };

}

This snippet shows how the data is displayed in my view using AngularJS:

<div ng-repeat="data in mydata ">{{data.name}} </div>

I would appreciate any guidance on synchronizing the response of the refresh method. Thank you.

Answer №1

If you're not familiar with promises, they can be a powerful tool in asynchronous programming. Essentially, a promise allows you to execute an operation that will eventually return a result, and then specify what should happen next once that result is available.

There are various libraries for working with promises, such as Angular's implementation of Q.

For example, consider a service method that retrieves data:

loadData: function(){
    return $http.get(url);
}

The $http.get() method within this service returns a promise, which means you can use it like this in your controller:

service.loadData()
.then(function(res){
    // res contains the retrieved data
 });

By utilizing promises, you can also implement features like showing a loading spinner while data is being retrieved and turning it off once the data is loaded.

If you want to learn more about using promises with Angular, check out this helpful video tutorial: egghead.io/promises

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

Creating a tailored regular expression for validating email addresses

Up to this point, I have crafted a regex pattern as Pattern="^(?=.*[a-zA-Z].*)([a-zA-Z0-9._%+-]+@([a-zA-Z0-9-]+[a-zA-Z0-9-]+(\.([a-zA-Z0-9-]+[a-zA-Z0-9-])+)?){1,4})$" that meets the following criteria: Not all characters should be numbers, ...

Loading only specific HTML list elements in segments

Within my Angular4 application, I am faced with a challenge involving a large list of li elements. The browser struggles to handle the thousands of li's being displayed when the user interacts with the ul element. This results in slow loading times an ...

Implementing momentLocalizer with moment.js in react-big-calendar alongside fullcalendar.js

I'm currently working with react-big-calendar and I require assistance in setting up localization as per the example provided on GitHub. import BigCalendar from 'react-big-calendar'; import moment from 'moment'; BigCalendar.setLo ...

uiRouter implementing an asynchronous templateProvider

I encountered a small issue while working on my UI state provider. I intended to use a function to retrieve a menu based on a user's access level, which is determined by an API call. Everything seemed fine initially. I set up a Restangular call to fe ...

What is preventing the items inside the <ul> element from displaying?

Struggling to grasp pagination, I can't figure out why the contents of "li" under the "ul" disappear while the "ul" container continues to display despite specifying in the JavaScript that only 6 should be visible on the page. The "ul" and "li" elemen ...

How can I dynamically load a 3D model (in JSON format) at the current location of the mouse using Three.JS?

I'm currently working on a feature that involves loading a 3D model based on the mouse's position. Utilizing jQuery drag and drop functionality for this purpose has helped me load the model onto the canvas successfully, but I'm facing issues ...

What is the correct way to properly enter a Svelte component instance variable?

Currently, I am delving into learning Svelte and specifically exploring how to bind to a component instance as demonstrated in this tutorial: As I progress through the tutorial, I am attempting to convert it to Typescript. However, I have encountered an ...

Utilize the string module from a JavaScript file in your React or Next.js project

Within my project structure, I have a file named "test.js" located in the "/constants" directory. The content of this file is as follows: const test = "test!" export default test In another part of my project, specifically within the "/pages" folder, I w ...

Guide on adding a username to the createUserWithEmailAndPassword authentication method in Firebase

I am currently working on implementing Username and Password Authentication in a web application built with react and firebase. However, being a beginner with firebase, I am having trouble finding detailed documentation on the process. I have come across F ...

Enabling individuals to transfer their content to Amazon S3

I have set up an S3 bucket named BUCKET in region BUCKET_REGION. I want to enable users of my web and mobile apps to upload image files to this bucket, with specific restrictions based on Content-Type and Content-Length (specifically, only allowing jpegs u ...

What is the method to retrieve the local filepath from a file input using Javascript in Internet Explorer 9?

I'm experiencing some issues with the image-preview function on IE9, similar to the example photo shown. This method is not functioning properly and throwing an error in IE9, while it works perfectly fine in IE6-8. I am looking for a way to retrieve ...

Dynamic content carousel

Exploring the world of jQuery for the first time and aiming to code logically, I am in the process of creating an upload site where users have the option to select "upload from computer" or "upload from URL". There are two links positioned above the conten ...

Can you provide a method for verifying an 'undefined' variable in AJAX queries?

How can we elegantly check if a variable is undefined in JavaScript? $.ajax({ type: method, url: url, success: function (data) { if (form != null || form != undefined){ data = $(form).serialize(); } var json ...

Learn how to toggle a specific div by clicking on an image generated from an ngFor loop in Angular version 11

One issue I am facing is that I have multiple sections containing image info and details. When I click on a specific image, the corresponding details should toggle. Everything works fine, however, if I click on another image without closing the previous ...

Resolving issues with JavaScript caused by Polymer updates

I am a novice when it comes to working with Polymer. From what I have gathered, there seems to be compatibility issues with Mozilla and Safari. After researching on StackOverflow, I found that adding addEventListener('WebComponentsReady', funct ...

Dynamic Filtering of HTML Dropdown Options Based on Another Dropdown Selection

I am facing an issue with multiple HTML dropdowns. My requirement is that upon selecting an option from one dropdown, the next dropdown should get automatically populated. The data to populate these dropdowns is fetched from a database using SQL statements ...

Drag and release: Place within invalid drop areas

I'm currently developing a drag-and-drop web application using Vue.JS and Vuex Store. The drag-and-drop functionality is based on the HTML Drag and Drop API as outlined in the Mozilla documentation. I have successfully implemented the Dropzone Compone ...

Is QA supported by LG WebOS 3.5 through webdriver?

I've been experimenting with Javascript ( nodejs ) and have successfully automated browser operations using selenium-webdriver on a local server. However, I am facing challenges when trying to automate tasks on my LG WebOS 3.5 TV. Does anyone know how ...

Vue.js navigation guards, restrict access to all unauthorized routes, grant entry to specific routes upon successful authentication

I'm currently working on implementing a navigation guard in Vue.js with a specific logic: I want to restrict access to all routes that require authentication and redirect users to the login page if they are not authenticated. The only exception is the ...

Disabling an HTML attribute on a button prevents the ability to click on it

In my React application, I have a button component that looks like this: <button onClick={() =>alert('hi')} disabled={true}>test</button> When I removed the disabled attribute from the browser like so: <button disabled>test& ...