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.