与AngularJS服务器轮询 [英] Server polling with AngularJS

查看:191
本文介绍了与AngularJS服务器轮询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习AngularJS。我第一次尝试,以获得新的数据每秒钟工作:

I'm trying to learn AngularJS. My first attempt to get new data every second worked:

'use strict';

function dataCtrl($scope, $http, $timeout) {
    $scope.data = [];

    (function tick() {
        $http.get('api/changingData').success(function (data) {
            $scope.data = data;
            $timeout(tick, 1000);
        });
    })();
};

当我在睡眠线程5秒钟模拟一个缓慢的服务器会等待更新的用户界面和设置其他超时之前的响应。问题是,当我重​​写使用角模块和DI为模块创建上面的:

When I simulate a slow server by sleeping the thread for 5 seconds it waits for the response before updating the UI and setting another timeout. The problem is when I rewrote the above to use Angular modules and DI for module creation:

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

这只有在服务器响应速度快的工作。如果有任何延迟它修建垃圾出1请求的第二而不等待一个响应,似乎清除的用户界面。我想我需要使用一个回调函数。我想:

This only works if the server response is fast. If there's any delay it spams out 1 request a second without waiting for a response and seems to clear the UI. I think I need to use a callback function. I tried:

var x = Data.get({}, function () { });

但得到了一个错误:错误:destination.push不是一个函数这是基于文档的 $资源但我并没有真正了解那里的例子。

but got an error: "Error: destination.push is not a function" This was based on the docs for $resource but I didn't really understand the examples there.

我如何让第二种方法工作的?

How do I make the second approach work?

推荐答案

您应该调用在回调查询<功能/ code>。

You should be calling the tick function in the callback for query.

function dataCtrl($scope, $timeout, Data) {
    $scope.data = [];

    (function tick() {
        $scope.data = Data.query(function(){
            $timeout(tick, 1000);
        });
    })();
};

这篇关于与AngularJS服务器轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆