code.cycling
code.cycling

Reputation: 1274

$watch a service when theres changes

I want to watch changes in my services like in my system logs when there's someone who login the getlogs function must trigger how to achieve this ???

dashboard.controller

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

dataservice.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);
  }
}

I've tried this but its not working

 $scope.$watch('dataservice.getLogs()', function () {
  getLogs();
}, true);

Upvotes: 0

Views: 55

Answers (2)

Marcus Höglund
Marcus Höglund

Reputation: 16801

This is a case for observable pattern where you subscribe for changes on your service

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

Then in your controller add a subscriber function to the service

dataservice.addSubscriber(function(){

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

NOTE: this can also be done with the RxJs library

Upvotes: 1

Fetrarij
Fetrarij

Reputation: 7326

if you want to check and get data's change from server, watching a service is not for that, use a polling service.

you check for every 1sec (for example) from a server:

example:

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

or much better:

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

Upvotes: 1

Related Questions