AngularJS和Servlet集成
问题描述:
我想调用一个函数,该函数通过链接从servlet返回一个json对象。AngularJS和Servlet集成
我的HTML链接,请拨打FTEST功能:
<td><a href="" ng-controller="minaplantaCtrl" ng-click="fTest(x.id_camion_descarga)">ver</a></td>
我的控制器:
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga){
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {$scope.descargas = response.descargas;});
$window.alert(JSON.stringify($scope.descargas));
};
});
当我按下首次的链接出现在警报 “未定义”
但当我第二次按时,如果我能看到在警报中返回的json对象
当我按下第一个链接时可能会发生什么?请帮助
感谢
答
这里的问题是你是在提醒$ scope.descargas因此它确实是没有定义还没有尝试改变它像这样的成功回调之外。
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga){
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {
$scope.descargas = response.descargas;
$window.alert(JSON.stringify($scope.descargas));
});
};
});
答
因为使用角$ HTTP每个服务器端请求是一个AJAX即异步调用服务器,你是假设你的警报方法的成功响应执行完成后调用。但这是错误的。
这就是承诺的概念来自Angular的地方。当您与服务器端的延迟执行该代码
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga) {
console.log("1");
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {
$scope.descargas = response.descargas;
console.log("2");
});
console.log("3");
$window.alert(JSON.stringify($scope.descargas));
};
});
所以,你会看到控制台日志的顺序为:,和。
因此,您的成功功能是在从服务器接收到响应时执行的。因此,第一次,descargas
变量中的值为空,但get使用第一个服务器响应进行存储,下一次显示前一个调用的值。