AngularJS anticipates the completion of a lone asynchronous request

Attempting to assign data to the scope after an asynchronous call.
There is an array named companies in the factory.

factory.getByCategoryId = function (id) {
  $http.get('http://localhost/campaign?access-token=12345&id=2').then(
    function (result) {
      factory.companies = [];
      if (result.data.length !== 0) {
        for (var index = 0; index < result.data.length; index++) {
          factory.companies.push(result.data[index]);
       }
      } else {
        console.log('Result is not set.', result);
      }
    },
    function (result) {
      console.log('Failed', result);
    }
  );
}

Function invocation:

$scope.closeModal = function (index) {
  if (index) {
    var promises = []

    promises.push(Service.getByCategoryId($scope.categories[index].id));

    $q.all(promises).then(function () {
      $scope.myItems = Service.all(); //return all from factory.companies

      $scope.refreshItems(); //this function refreshes the DOM using myItems
    });
  }
}

The first time this function is called, factory.companies remains unchanged, but it gets updated on subsequent calls. There seems to be a delay before the update takes place, but I'm uncertain how to address it.

Answer №1

I recommend simplifying your Service function by returning only the $http.

Update your factory like this:

factory.getByCategoryId = function (id) {
    return $http.get('http://localhost/campaign?access-token=12345&id=2');
}

Then modify your function to call the Service:

$scope.closeModal = function (index) {
    Service.getByCategoryId($scope.categories[index].id).then(
    function (result) {
        if (result.data.length) {
            angular.forEach(result.data, function(value) {
                $scope.myItems.push(value);
            });
            $scope.refreshItems();
        } else {
            console.log('Result is not set.', result);
        }
    },
    function (result) {
      console.log('Failed', result);
    }
};

An alternative approach is to update your service function to resolve a promise:

factory.getByCategoryId = function (id) {
    return $q(function (resolve, reject) {
        $http.get('http://localhost/campaign?access-token=12345&id=2').then(
            function (result) {
                factory.companies = [];
                if (result.data.length !== 0) {
                    for (var index = 0; index < result.data.length; index++) {
                        factory.companies.push(result.data[index]);
                    }
                    resolve(factory.companies);
                } else {
                    reject('Result is not set.', result);
                }
            },
            function (result) {
                console.log('Failed', result);
            }
        );
    });
}

Now you can use it like this:

$scope.closeModal = function (index) {
    Service.getByCategoryId($scope.categories[index].id).then(function(result) {
    $scope.myItems = result;
    $scope.refreshItems();
}, function(result) {
    console.log(result);
});

Answer №2

If

Service.getByCategoryId($scope.categories[index].id)

Is returning a promise then

$scope.closeModal = function (index) {
if (index) {
    Service.getByCategoryId($scope.categories[index].id).then(function (res) {
        $scope.myItems = Service.all(); //return all from factory.companies
        $scope.refreshItems(); //this function refreshes the DOM using myItems
    }, function (res) {
        // Error Handling
    })
 }
}

In Case You Need More Info ::

app.factory('Service', function ($http) {
return {
    // Function to get a promise
    getByCategoryId_promise: function () {
        // Providing the promise, additional implementation may be needed for execution
        return $http.get("URL GOES HERE");
    },
    // Function to get results from a promise
    getByCategoryId: function () {
        // This Function waits till the HTTP call is resolved and then sends the result
        return $http.get("URL GOES HERE").then(function (res) { }, function (res) { })
    },
}
})

Answer №3

    When calling Service.getByCategoryId($scope.categories[index].id), the result is added to the promises array.

The value returned by Service.getByCategoryId is asked for.

Since there is no explicit return statement in Service.getByCategoryId, its value is considered as undefined.

In order to make Service.getByCategoryId return a promise (most likely from $http.get), adjustments need to be made.

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

Using jQuery, you can disable an option upon selection and also change its border color

learn HTML code <select name="register-month" id="register-month"> <option value="00">Month</option> <option value="01">January</option> <option value="02">February</option> <option value="03"& ...

JavaScript sorted arrays are an efficient way to keep data

In my dataset, I have an array of objects representing various products. Each product object includes a field called ratingReviews and another field called price, which can either be a string or an object. If the price is represented as an object, it conta ...

Matching nodes to selectors is a breeze with Angular JS and jqLite

Currently, I am in the process of integrating a few jQuery functions into jqLite to avoid loading the entire jQuery library when working with my angular applications. Following the approach outlined by Ben Nadel in his insightful article. However, I have ...

Tips for altering a key within a tree-view:

I am working with a potentially infinite tree-view array: type Tree = { id: number; name: string; email: string; children: Tree[]; }; const tree: Tree[] = [ { id: 1, name: 'Truck', email: '@mail', children ...

Tips for locating a file using javascript

My application scans a folder and displays all folders and HTML files inside it in a dropdown menu. It also shows any HTML files inside an iframe. There is one file named "highlighted.html" that should not appear in the dropdown menu, but if it exists in t ...

Unable to utilize the ng-disabled directive

Although this question may seem redundant, rest assured that I have exhausted all possible solutions. The issue lies in a disabled button using ng-disabled. I have a variable in the $scope that triggers a change in the ng-disabled attribute, but it fails t ...

How is the rendering of a confirm/alert decided?

While browsing, I stumbled upon this intriguing query related to alerts and confirm dialogs, such as the one generated by alert('Hello World!'). My quest was to find a method to modify the text on the 'ok' and 'cancel' buttons ...

"Exploring the benefits of using nested mapping for res.json() in an Express application

I have been developing an express application (server-side) that offers movie information to users, and I am attempting to send a JSON response in the following format: { "title": "Star Trek: First Contact", "year": 1996, ...

Creating a list that renders responsively using ReactJS

I'm currently working on implementing a responsive search bar that filters through a list of pure components (up to 100 components displayed at once). However, I've noticed there is a slight half-second delay between typing the first letter and s ...

Using JavaScript to interact with text elements in external SVG documents

When it comes to creating an SVG within HTML and assigning specific IDs to text elements for easy access, everything works smoothly. For example, I can easily retrieve the ID using: let callQSO = document.getElementById("QSOcall").value; and th ...

What are the benefits of using async if I must also utilize await in my code?

I've been grappling with this question for quite some time and have yet to find a satisfactory explanation for it. Consider the following async method: public async Task<bool> MyMethod() { // Some logic return true; } public async voi ...

Interacting Between PHP and Javascript

<form action="../"> <select onchange="window.open(this.options[this.selectedIndex].value,'_top')"> <option value="">Choose a zipcode </option> <option value="92507">92507</option> <option value=" ...

Tips on deleting information from an object by utilizing Chrome storage mechanisms

In the chrome storage, I have an object structured as follows: { "planA": { 123: {key: 'some key'} 124: {key: 'some other key'} }, "planB": { 223: {key: 'some key'} 234: { ...

What is the reason behind only the initial click boosting the vote count while subsequent clicks do not have the same

In this snippet of code: //JS part echo "<script> function increasevotes(e,location,user,date,vote) { e.preventDefault(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState ...

Processing files from input file

I'm currently attempting to loop through all the files selected in the file input field, following a sample code. While I am able to fetch values from the upload control, I'm facing issues while trying to iterate through them. I'm unsure if ...

What repercussions come from failing to implement an event handler for 'data' events in post requests?

If you take a look at the response provided by Casey Chu (posted on Nov30'10) in this particular question: How do you extract POST data in Node.js? You'll find that he is handling 'data' events to assemble the request body. The code sn ...

The parseJSON function is not compatible with AJAX requests

I am attempting to use ajax and retrieve JSON data in WordPress. Here is my Ajax code: $.ajax({ type: "POST", dataType : 'html', url: "/wp-content/themes/myproject/ajax/otros_alojamientos.php", da ...

What causes variations in running identical code between the Node environment and the Chrome console?

let myName = "World"; function functionA() { let myName = "FunctionA"; return function() { console.log(this.myName); } } functionA()(); Executing the code above in my terminal with node results in undefined, while running it in Chrom ...

The Javascript function I created references a variable that seems to be undefined in the code

Recently, I discovered a function that is triggered with an onclick event using "openNav()" from an HTML element. Below is the code snippet for this function: function openNav() { document.getElementById("nav-drawer").classList.add("nav-drawer-open"); ...

Designing geometric forms using the vertices of a Sphere in ThreeJs

My current project involves creating shapes based on vertices that have already been generated using a formula. I have successfully connected lines between these vertices using a threejs method, but now I want to take it a step further and create map tiles ...