【问题标题】:angular js update json on interval and update the viewangular js按间隔更新json并更新视图
【发布时间】:2014-04-20 11:45:22
【问题描述】:

我一直在尝试在 Internet 上找到一种解决方案,以便能够在设定的时间间隔内更新我的 $http json 请求,同时让它使用新数据更新我的绑定。

我已经看到一些使用 $timeout 的示例,但无法使其正常工作,只是想知道最好的方法是什么。还能够使用下拉的新数据更新视图是我似乎无法解决的问题,因为我无法提出新请求。

这是我当前的构建。

app.js 文件,这只是显示 json 的初始获取。

    var myApp = angular.module('myApp', ['ngRoute']);

    myApp.controller('MainCtrl', ['$scope', '$http',
        function($scope, $http, $timeout) {
            $scope.Days = {};

            $http({
                method: 'GET',
                url: "data.json"
            })
                .success(function(data, status, headers, config) {
                    $scope.Days = data;
                })
                .error(function(data, status, headers, config) {
                    // something went wrong :(
                });

        }
    ]);

HTML 设置:

<ul ng-controller="MainCtrl">
  <li class="date" ng-repeat-start="day in Days">
    <strong>>{{ day.Date }}</strong>
  </li>

  <li class="item" ng-repeat-end ng-repeat="item in day.Items">
    <strong>>{{ item.Name }}</strong>
  </li>
</ul>

【问题讨论】:

  • 我不明白你想达到什么目的。从您的示例中,您调用返回 Days 对象的 http 异步调用。 ngRepeat 指令监听 Days 变化(有私人观察者)并显示新数据。有什么问题?谢谢,
  • 我从服务器请求的 json 数据一直在更新,我的印象是我需要设置一个超时函数来调用 $http 来获取更新的 json 数据,然后更新当前观点。也许我对角度的工作方式仍然有些误解。我很抱歉。
  • 据我了解,您希望在循环 http 中运行一些延迟,对吧?
  • 是的,就像一个投票者。每 x 秒请求一次 json,然后在数据发生变化时更新视图。
  • 使用 $interval 让功能在几分钟后生效......并且您的需求推送服务优于 $interval

标签: javascript json angularjs


【解决方案1】:

我会使用$timeout。

如您所知,$timeout 返回承诺。所以当 promise 解决后,我们可以再次调用方法 myLoop。

在以下示例中,我们每 10 秒调用一次 http。

var timer;

function myLoop() {
    // When the timeout is defined, it returns a
    // promise object.
    timer = $timeout(function () {
        console.log("Timeout executed", Date.now());
    }, 10000);

    timer.then(function () {
        console.log("Timer resolved!");

        $http({
            method: 'GET',
            url: "data.json"
        }).success(function (data, status, headers, config) {
            $scope.Days = data;
            myLoop();
        }).error(function (data, status, headers, config) {
            // something went wrong :(
        });
    }, function () {
        console.log("Timer rejected!");
    });

}

myLoop();

附注:

当控制器被销毁时一定要调用$timeout.cancel( timer );

// When the DOM element is removed from the page,
// AngularJS will trigger the $destroy event on
// the scope. 
// Cancel timeout
$scope.$on("$destroy", function (event) {
    $timeout.cancel(timer);
});

演示Fiddle

【讨论】:

  • 使用 $timeout 是否比使用 $interval 有好处?
  • @Anks 在我们的例子中,我认为$timeout 更好,因为您的方法是异步调用。 $interval 确实便宜,您可以设置标志以不触发摘要循环。但是在我们的例子中,我们只有在成功回调时才会触发下一个调用。如果请求失败或卡住会发生什么,$interval 将继续迭代 http 调用。因此,您可以选择哪个更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
  • 2012-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
相关资源
最近更新 更多