普通网友 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);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀