javascript - Angular : Update data every few seconds

标签 javascript angularjs angularjs-directive intervals

也许这个问题已经被问过了,但我搜索并尝试了整个下午的大部分时间都没有成功,所以我真的希望有人能帮助我解决这个问题。

我希望能够每隔几秒更新我在工厂服务中设置的 $http.get() - 我的数据。

我在我的代码中添加了一些注释,还留下了一些旧东西让你们看看我尝试了什么。 (旧东西也注释掉了)

我的代码:

    ovwid.factory('recentClients', [
    '$http', 
    '$rootScope',
function ($http, $rootScope) {

    var apiURL = '/plugins/data/get_client.php';
    var promise;

    var recentClients = 
    {
        async: function() 
        {
            if ( !promise ) 
            {   
                // $http returns a promise, which has a 'then' function, which also returns a promise
                promise = 
                $http.get(apiURL)
                    .then(function (response) {
                    // The then function here is an opportunity to modify the response
                    // The return value gets picked up by the then in the controller.
                    return response.data;
                });
            }
            // Return a promise to the controller
            return promise;
        }
    }
    return recentClients;
}]);


ovwid.controller(‘client’Ctrl, [
    '$scope',
    'recentClients',
    '$interval',
function ($scope, recentClients, $interval) {

    $scope.loading = true;

    function reloadData() {
        // a call to the async method
        recentClients().async().then(function(data) {
            // console.log(data);
            $scope.loading = false;
            $scope.client = data;
        });
    }

    // Initizialize function
    reloadData();

    // Start Interval
    var timerData = 
    $interval(function () {
        reloadData();
    }, 1000);  

    // function myIntervalFunction() {
    //     var cancelRefresh = $timeout(function myFunction() {
    //         reloadData();
    //         console.log('data refres')
    //         cancelRefresh = $timeout(myFunction, 5000);
    //     },5000);
    // };

    // myIntervalFunction();

    // $scope.$on('$destroy', function(e) {
    //         $timeout.cancel(cancelRefresh);
    // });
}]); // [/controller]

最佳答案

我看到了几个问题。

首先:

if ( !promise ) 只会在第一次返回 true。您正在将其分配给 $http 调用。

其次:

您永远不会访问工厂中的 async 方法。 您需要从工厂返回它 return recentClients.async 或从作用域调用它 recentClients.async().then(..

关于javascript - Angular : Update data every few seconds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24956641/

相关文章:

javascript - 根据值处理 JSON 对象/数组

javascript - 我想在单击 "Add To Chart"并且通知成功或失败时使用 ajax laravel 发出通知

javascript - Cypress:在多个 API 测试中重复使用身份验证 token

javascript - AngularJS module.controller 与 $controllerProvider.register

javascript - 在 AngularJS 的 $valid 中排除某些字段进行验证

angularjs - 如何传递客户端数据以表示调用远程 url 并获取响应

angularjs - 如何在 AngularJS 中生成即时指令?

javascript - 如何在expressjs中的AJAX请求(没有Jquery)中发送csrf token ?

javascript - 印度格式的 Angular 货币过滤器

javascript - 使用 Angular 格式化程序/解析器