0

My controller has the following code:

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);});

But when I write $scope.allLogs to console it shows empty object but when I do console.log($scope); and view the allLogs array I can see the data.

The response.data is:

[
{"id" : 001, "name" : "name", "age" : 20},
{"id" : 002, "name" : "name", "age" : 21},
{"id" : 003, "name" : "name", "age" : 22},
{"id" : 004, "name" : "name", "age" : 23}
]

What am I doing wrong?

harnamc
  • 541
  • 6
  • 20

2 Answers2

1

You have placed the console.log outside of the $http call which is asynchronous. Hence by the time you write to the console, you haven't got the asynchronous response back from your server and so log will write an empty object. Move the console.log inside the $http success callback as below,

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);});
});
Aruna
  • 448
  • 3
  • 12
0

Because console.log() is executing before the value is assigned in the $scope.allLogs object. try to log inside the then(); This is happening due to asynchronous behaviour of $http which is an ajax call internally;