I am currently developing a straightforward application that involves the following steps: 1. The user provides 2 parameters and clicks a button 2. Angular communicates with an external JAVA Servlet that sends back JSON data 3. The application displays the JSON string on the screen
However, I have encountered a problem where nothing happens when I click the button. I suspect that this issue arises because the asynchronous call returns a null variable.
Key pieces of code:
controllers.js
function myAppController($scope,kdbService) {
$scope.buttonClick = function(){
var dat = kdbService.get($scope.tName,$scope.nRows);
$scope.data = dat;
}
}
services.js
angular.module('myApp.services', []).factory('kdbService',function ($rootScope,$http){
var server="http://localhost:8080/KdbRouterServlet";
return {
get: function(tname,n){
var dat;
$http.jsonp(server+"?query=krisFunc[`"+tname+";"+n+"]&callback=JSON_CALLBACK").
success(function(data, status, headers, config) {
console.log("1");
console.log(data);
dat=data;
}).
error(function(data, status, headers, config) {
alert("ERROR: Could not get data.");
});
console.log("2");
console.log(dat);
return dat;
}
}
});
index.html
<!-- Boilerplate-->
<h1>Table Viewer</h1>
<div class="menu" >
<form>
<label for="tName">Table Name</label>
<input id="tName" ng-model="tName"><br>
<label for="nRows">Row Limit</label>
<input id="nRows" ng-model="nRows"><br>
<input type="submit" value="Submit" ng-click="buttonClick()">
</form>
</div>
{{data}}
<!-- Boilerplate-->
Upon executing the code and clicking the button, nothing seems to occur. However, when I check the log, the following output is displayed:
2
undefined
1
Object {x: Array[2], x1: Array[2]}
Evidently, the success function returns after the get function has already completed, resulting in the $scope.data variable being undefined while the data from the jsonp call is accessible.
Is there a more appropriate approach to resolving this issue? Many tutorials suggest assigning the data to the $scope variable within the success function to bypass this problem. I prefer to keep my service detached if feasible.
Any guidance would be greatly appreciated.