0

In my app I have a service that asynchronously returns cached value:

    .service('StateService', [
        '$q',
        function ($q) {
            var value;
            // ...
            // ...
            function getValue() {
                return $q.when(value);
            }
            // ...
            // ...
            return {
                getValue: getValue
                // ...
                // ...
            };
        }
    ]);

Static variable "value" is updated via setter in the same service. It is a requirement to have getter getValue() that works asynchronously - the idea is to implement an id cache in the future.

In the main controller I need to $watch changes to StateService.getValue() and update scope with new value if it was changed.

Is there a possibility to $watch promises (that are not actually a resource calls, but just a static value wrapped in a promise) with $scope.$watch?

Maybe by unwrapping them in every digest and comparing old a new value?

Giuseppe Cazzato
  • 99
  • 1
  • 1
  • 11
  • An alternative would be to raise an event whenever the cache changes and have your controllers listen for this event as opposed to watching the cache? – Ankh Dec 13 '16 at 11:05
  • Please, show how this is supposed to be used, there's not enough information. There's no reason for getValue to be a promise. If it is should be asyncronous, please, show that. It seems that you're trying to use promises for a thing they were never intended for. Consider using observables (e.g. RxJS) instead. – Estus Flask Dec 13 '16 at 13:33
  • Does your asynchronous API execute its callback once or multiple times? Promises are containers for **one-time** values that are returned in the future. Watchers execute their callbacks multiple times. – georgeawg Dec 13 '16 at 16:36

1 Answers1

1

Is not possible, the best option is to do the $watch in the $scope in the q is storing the value of your service