The $http requests require time which varies depending on the server, some may take a few milliseconds, and some may take up to a few seconds. Often the time required to retrieve the data from a request is critical. Assuming the response value is an array of names, consider the following example:
Incorrect
$scope.names = [];
$http({
method: 'GET',
url: '/someURL'
}).then(function successCallback(response) {
$scope.names = response.data;
},
function errorCallback(response) {
alert(response.status);
});
alert("The first name is: " + $scope.names[0]);
Accessing $scope.names[0]
right below the $http request will often throw an error - this line of code executes before the response is received from the server.
Correct
$scope.names = [];
$scope.$watch('names', function(newVal, oldVal) {
if(!(newVal.length == 0)) {
alert("The first name is: " + $scope.names[0]);
}
});
$http({
method: 'GET',
url: '/someURL'
}).then(function successCallback(response) {
$scope.names = response.data;
},
function errorCallback(response) {
alert(response.status);
});
Using the $watch service we access the $scope.names
array only when the response is received. During initialization, the function is called even though $scope.names
was initialized before, therefore checking if the newVal.length
is different than 0 is necessary. Be aware - any changes made to $scope.names
will trigger the watch function.