Exploring the power of Angular JS promises through ng-repeat

My current project involves fetching latitude and longitude coordinates from a postcode using an API, then utilizing those coordinates to retrieve data on street level crimes near that location on a specific date through the UK police API. However, I have encountered an issue where ng-repeat does not function as expected. It seems that this is due to the $http request not receiving any response when the page loads; console logging returns undefined initially, but after a setTimeout delay of two seconds, the desired data is retrieved.

Below is an excerpt of my code:

function PostCodeCtrl($scope, Server, $location, $routeParams){

this.postcode = $routeParams.postcode;

if(this.postcode){
    this.title = "dasdasd";
    this.crimes = undefined;

    Server.get("http://api.postcodes.io/postcodes/" + this.postcode)
        .then(function(response){

        this.response = response.data;

        if(response.data.status === 200){

            Server.get('http://data.police.uk/api/crimes-street/all-crime?lat='+ 
                        this.response.result.latitude +
                        '&lng='+
                        this.response.result.longitude+
                        '&date=2013-01').then(function(response){

                this.crimes = response.data;

            });

        }

    });

    console.log(this.crimes); //returns undefined
    setTimeout(function(){
        console.log(this.crimes); //returns JSON object
    }, 2000);
}else{

    $location.path('/');

}

}

<ul>
    <li ng-repeat="crime in postcode.crimes">
        {{crime.category}}
    </li>
</ul>

I am also puzzled by the concept of promises. Despite watching numerous tutorials advocating for promises to eliminate pyramid code structures like in the following example:

(function($) {
  $(function(){
    $("button").click(function(e) {
      $.get("/test.json", function(data, textStatus, jqXHR) {
        $(".list").each(function() {
          $(this).click(function(e) {
            setTimeout(function() {
              alert("Hello World!");
            }, 1000);
          });
        });
      });
    });
  });
})(jQuery);

I fail to see how promises effectively address nesting issues, as thens still lead to a hierarchical structure similar to what I have experienced in my initial code snippet.

Answer №1

Here are solutions for two common programming challenges:

How to retrieve async data in a loop using AngularJS

If you are using ng-repeat in AngularJS and need to load data asynchronously, make sure to set the data before rendering the view. For example:

<div ng-repeat="item in items">
  {{item.title}}
</div>

To achieve this, you can use promises with $http like so:

$http.get("data.json").then(function(response){
   $scope.items = response.data;
});

console.log($scope.items); // undefined initially

How to avoid callback hell when chaining promises

Promises can be chained in JavaScript to simplify asynchronous code execution. Here's an example:

$http.get("/someService")
  .then(function(response){
     var data = response.data;
     return $http.get("/someOtherService", { d: data });
  })
  .then(function(response){
    var data2 = response.data;

    // handle data

    return finalData;
  };

You can encapsulate this logic in a service:

.factory("Svc", function($http){
    getFinalData: function(){
       return $http.get("/someService").then(function(response){
         // continue chaining as needed
       });
    }
})

Then, in your controller, utilize the service method:

.controller("MainCtrl", function(Svc){
   Svc.getFinalData().then(function(data){
     $scope.items = data; // now you can use ng-repeat
   });
});

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

When the disk space is insufficient, the createWriteStream function will not trigger an error event if the file is not completely written

One challenge I'm encountering involves using createWriteStream: Imagine I have a large 100mb file that I want to write to another file on the disk. The available space on the disk is only 50mb. Here's my code snippet: const fs = require(&a ...

React does not allow objects as child elements. Instead, render a collection of children by using an array

Encountering an error with this React class Error: Objects are not valid as a React child (found: object with keys {_id, name}). If you meant to render a collection of children, use an array instead. Is there anything amiss here? I am passing the movies ...

Guide to displaying numerous points on mapbox by utilizing a for each loop statement

I have a 2D array containing longitudes and latitudes that I need to map using MapBox. The example I found only demonstrates plotting two points, so I attempted to use a for-each loop to iterate through my 2D array and plot all the points. However, I enco ...

What is the best way to incorporate user-provided values into a dynamic URL?

I am trying to create a feature where users can input a value and then click a button that will take them to a URL tailored to their entry. Here is my current code, but I am facing an issue - the user_input data does not seem to be passed to the URL when ...

What is the most effective way to dynamically incorporate external input into a SlimerJS script?

Could use some assistance with SlimerJS. My current program requires intermittent input from stdin to proceed with the next task. The code below functions effectively when using PhantomJS+CasperJS for reading external input, but encounters difficulties wi ...

There are three pop-up windows displayed on the screen. When each one is clicked, they open as intended, but the information inside does not

Every button triggers a unique modal window Encountering an unusual problem with Bootstrap 5 modal functionality. Within a webpage displaying a list of database entries (refer to the screenshot), each entry features three buttons to open corresponding mod ...

Is it possible to efficiently iterate through map keys in axios using Vue.js?

Currently, I am working on Vue.js exercises that I have created. I am successfully populating a table with data from a JSON API, but I have encountered a challenge. The API contains multiple keys with similar names (strIngredient1, strIngredient2, strIngre ...

Unable to proceed, WISTIA upload frozen at 100% complete

I recently integrated the Wistia API for video uploads. Everything seemed to be working fine as per the Wistia documentation until I encountered an issue. After uploading a video file, the progress bar would reach 100%, but then an error was logged in the ...

Error: Django unable to load jQuery library

Hey there! I have a template that includes my JavaScript code. However, when I view the template in a browser, it doesn't provide the interaction I was hoping for. Upon checking the console, I see the following error messages: Error: Bootstrap's ...

Switch directions following a successful status code of 200

After successfully logging in (with a status of 200), I want to change my route to /expenses. async SendLogin() { const response = await axios.post("api/auth/login", { email: this.email, password: this.password, }); localStorage.setItem("toke ...

Manually sending the form via Ajax for submission

I'm facing an issue where I am trying to utilize ajax to call a servlet upon form submission. However, the ajax call is not being triggered and the page ends up reloading. To solve this problem, I have set up a manual trigger for the form submission, ...

What is the best way to automatically show scrollbars when a page loads using JavaScript?

How can I make the vertical scrollbar appear as soon as the page loads using javascript? I am currently using a jquery slide toggle animation that causes the vertical scrollbar to show up because it makes the page longer. However, when the scrollbar appear ...

vee-validate remains consistent in its language settings

Having trouble changing the error message in vee-validate, any suggestions on how to fix this? import VeeValidate from "vee-validate"; import hebrew from "vee-validate/dist/locale/he"; Vue.use(VeeValidate, { locale: "he", dictionary: { he: { me ...

determining the overall page displacement

I'm working with this code and I need help using the IF condition to check if the total page offset is greater-than 75%. How can I implement that here? function getLocalCoords(elem, ev) { var ox = 0, oy = 0; var first; var pageX, pageY; ...

I am experiencing technical difficulties with my API resulting in a 500 Internal Server Error

My application involves managing products using CRUD operations. I am able to successfully make an HTTP request to the /api/deleteProduct route in order to delete a product based on its ID. However, the issue lies with creating a new product as the functi ...

What is the best way to extract keys from a hash in Ruby using a Javascript string?

I am currently developing a command line tool using Ruby that is designed to parse JSON data from diverse sources and perform certain operations on the retrieved information. To make it user-friendly, I have incorporated a feature where users can configure ...

Attributes required are not functional on mobile devices

Good day! I have encountered an issue with the required attribute on a form on my website. It seems to be working perfectly on my browser, but not on mobile devices. Has anyone else experienced difficulties with jQuery, JavaScript, or Node packages? <f ...

Executing a query with a `has many` relationship in MongoDB: Step-by-step guide

In my setup with Node, Express, and backbone, I am successfully retrieving records from MongoDB collections using simple queries. However, I am struggling to understand how to query more complex data, such as the one below: db.employees.aggregate( [ ...

Creating an Engaging Data Visualization: Blending Candlestick Insights with Line Graphs

I'm attempting to display a moving average on a candlestick chart, but I'm facing an issue where the path of the line is not fully appearing on the SVG canvas that I've created. I've searched through various posts to understand how to o ...

iterate through all the items in the radioButton collection

Hello, I am looking to iterate through this object and display checkbox values along with their indices. data: [ { key1: 'last 6 months' }, { key2: 'last 30 days' } ] I would like to creat ...