普通网友 2016-02-11 19:02
浏览 28

AngularJs $ interval服务

I'm a beginner in Angularjs and so I would like ask you if there is a better way for solve my issue.

I need to update, for example, every 30 seconds the content of a <div> with an ajax call.

HTML

<div>
    <div>{{test.value}}</div>
</div>

My idea was use $interval on a service as following:

.service('eedisplayService', function($q, $http, $interval){
    this.getData = function(url, variable){
        $interval(function (){
            var deferred = $q.defer();
             $http.get(url)
            .success(function(data){
                if (data){
                    variable.value = data
                } else {
                    deferred.reject('Wrong response');
                }
            })
            .error(function(){
                deferred.reject();
            });
            return deferred.promise
        },30000);
    }

});

And call service from controller like this:

.controller('displayCtrl', function($scope, config, eedisplayService){

    var url = "myUrl";

    $scope.test = {value : "" };

    eedisplayService.getData(url, $scope.test);

});

Is it a fully AngularJs approach? The code works, but is a good choice call a service with an $interval from controller? Is not better call it from config for example?

I checked out a lot of examples, but I don't really understand what is the best way to do this.

Thanks so much.

Regards

  • 写回答

1条回答 默认 最新

  • weixin_33724059 2016-02-11 19:53
    关注

    you could think about putting the $interval functionality in your controller so your service could be more generic/reusable.

    Also $http returns a promise on it's own so you don't necessarily need to do that manually:

    // your service 
    .service('eedisplayService', function($http){
      this.getData = function(url) {
        return $http.get(url);
      }
    }); 
    
    
    // controller 
    ...
    $interval(function() {
      eedisplayService.getData(...)
      .then(function(response) {
        // update the content in the view 
      })
    }, 30000);
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料