代码之家  ›  专栏  ›  技术社区  ›  code.cycling

$有变化时观看服务

  •  0
  • code.cycling  · 技术社区  · 8 年前

    当有人登录getlogs函数时,我想观察我的服务中的变化,比如我的系统日志中的变化,必须触发如何实现这一点???

    仪表板控制器

    function getLogs() {
      return dataservice.getLogs().then(function (data) {
        vm.logs = data;
        return vm.logs;
      });
    }
    

    数据服务。js公司

    function getLogs() {
      return $http.get('/api/timeLogs')
        .then(success)
        .catch(fail);
    
      function success(response) {
        return response.data;
      }
    
      function fail(e) {
        return exception.catcher('XHR Failed for getPeople')(e);
      }
    }
    

    我试过了,但没用

     $scope.$watch('dataservice.getLogs()', function () {
      getLogs();
    }, true);
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   Marcus Höglund    8 年前

    这是一个可观察模式的例子,您在其中订阅服务的更改

    app.service('dataservice', function($http) {
        var subscribers = [];
        var addSubscriber = function(func){
            subscribers.push(func);
        }
        var notifySubscribers = function(){
            for(var i = 0; i< subscribers.length; i++){
                subscribers[i](); //invoke the subscriber
            }
        };
    
        var addLog = function(){
            //let's say that the logs are added here
    
            //then notify the subscribers that a new log has been added
            notifySubscribers();
        };
    
        var getLogs = function() {
          return $http.get('/api/timeLogs')
            .then(success)
            .catch(fail);
    
          function success(response) {
            return response.data;
          }
    
          function fail(e) {
            return exception.catcher('XHR Failed for getPeople')(e);
          }
        };
    
        return {
            addSubscriber: addSubscriber,
            addLog: addLog,
            getLogs: getLogs
        }
    });
    

    然后在控制器中向服务添加订户功能

    dataservice.addSubscriber(function(){
    
        console.log('new log added');
        dataservice.getLogs();
    });
    

    注意:这也可以通过 RxJs 图书馆

        2
  •  1
  •   Fetrarij    8 年前

    若您想检查并从服务器获取数据的更改,那个么观看服务并不是为了这个目的,可以使用轮询服务。

    您每1秒(例如)从服务器检查一次:

    例子:

    $interval(function() {
        dataservice.getLogs().then(function(data) {
            vm.logs = data;
        });
    }, 1000);
    

    getLogs = function () {
      dataservice.getLogs().then(function(data){
        vm.logs = data;
        $timeout(getLogs, 1000)
      });
    }