我的控制器有以下代码:
app.controller("weeklyLogViewer", function ($scope, $http){
$scope.allLogs = {};
$http({
method: 'POST',
url: '../Utilities/WeeklyLog.php',
data: $scope.dateSelected,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response)
{
$scope.allLogs = response.data;
});
console.log($scope.allLogs);});
但是当我向控制台写$scope.allLogs
时,它显示空对象,但当我console.log($scope);
并查看allLogs数组时,我可以看到数据。
response.data是:
[
{"id" : 001, "name" : "name", "age" : 20},
{"id" : 002, "name" : "name", "age" : 21},
{"id" : 003, "name" : "name", "age" : 22},
{"id" : 004, "name" : "name", "age" : 23}
]
我做错了什么?
答案 0 :(得分:0)
因为在$ scope.allLogs对象中分配值之前正在执行console.log()。尝试登录then(); 这是由$ http的异步行为引起的,这是内部的ajax调用;
答案 1 :(得分:0)
您已将console.log置于$ http调用之外,该调用是异步的。因此,当您写入控制台时,您没有从服务器返回异步响应,因此日志将写入一个空对象。将console.log移动到$ http成功回调中,如下所示,
app.controller("weeklyLogViewer", function ($scope, $http){
$scope.allLogs = {};
$http({
method: 'POST',
url: '../Utilities/WeeklyLog.php',
data: $scope.dateSelected,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response)
{
$scope.allLogs = response.data;
console.log($scope.allLogs);});
});