Currently, I am delving into AngularJS to expand my knowledge. My initial attempt at retrieving new data every second proved successful:
'use strict';
function dataCtrl($scope, $http, $timeout) {
$scope.data = [];
(function tick() {
$http.get('api/changingData').success(function (data) {
$scope.data = data;
$timeout(tick, 1000);
});
})();
};
Upon trying to replicate a sluggish server by delaying the thread for 5 seconds, I noticed that it waits for the response before updating the UI and setting another timeout. However, when I refactored the code to leverage Angular modules and Dependency Injection for module creation, encountered an issue:
'use strict';
angular.module('datacat', ['dataServices']);
angular.module('dataServices', ['ngResource']).
factory('Data', function ($resource) {
return $resource('api/changingData', {}, {
query: { method: 'GET', params: {}, isArray: true }
});
});
function dataCtrl($scope, $timeout, Data) {
$scope.data = [];
(function tick() {
$scope.data = Data.query();
$timeout(tick, 1000);
})();
};
The revised code only functions effectively with prompt server responses. In case of any delay, it continuously sends out requests without waiting for a response, ultimately causing the UI to clear. I suspect utilizing a callback function could resolve this issue. I experimented with:
var x = Data.get({}, function () { });
However, I encountered an error: "Error: destination.push is not a function". My attempt was based on the examples provided in the $resource documentation, which I found somewhat confusing.
How can I rectify the shortcomings in my second approach?