0

I'm learning how to use angulars $interval by building a simple app that generates random string every second (inside a service) and returns it to the controller. However, I cant get the data. I am able to console.log it inside the function call, but not in the calling function inside the controller. What am I missing? I read here, but still dont get the point.

The controller:

angular.module("app").controller("authorC", function ($scope, WebService) {

    $scope.generate = function () {
        console.log("generating..");

        WebService.generateRandom().then(function (y) {
            console.log(y);
        });
    };
    $scope.stop = function () {
        WebService.stopGen();
    };
});

The service:

angular.module("app").service("WebService", function ($http, $interval) {

    function makeid() {
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        for (var i = 0; i < 5; i++)
            text += possible.charAt(Math.floor(Math.random() * possible.length));

        return text;
    }

    var genInterval;

    this.generateRandom = function () {
        genInterval = $interval(function () {
            return makeid();
        }, 1000);

        return genInterval;
    };

    this.stopGen = function () {
        $interval.cancel(genInterval);
        console.log("Stopped");
    }
});
Community
  • 1
  • 1
Alex
  • 1,982
  • 4
  • 37
  • 70
  • 1
    Explained in the documentation: https://docs.angularjs.org/api/ng/service/$interval. The promise will never be resolved (since the interval never stops, except at cancellation). It will be notified, though. – JB Nizet Feb 28 '17 at 15:08
  • Promises are not suitable for streams of data. Promises are objects that resolve only **once**, fulfilled or rejected. In functional programming, they are considered immutable objects. Their `.then` method always returns the same data or error. **For streams** use instead [rx-angular - Reactive Extensions Bindings for AngularJS](https://github.com/Reactive-Extensions/rx.angular.js). – georgeawg Feb 28 '17 at 19:39

1 Answers1

0

$interval returns a promise that will get notified on each iteration, resolved when the timer finished to run (interval is completed) or rejected if the interval was cancelled. https://docs.angularjs.org/api/ng/service/$interval

You can't use it to get a return value of the function that the interval runs. I'm not sure what you are trying to achieve, but you can for example save the randomValue on your service (and replace it on each iteration), so it will be able to access it from outside.

Ben Bracha
  • 1,377
  • 2
  • 15
  • 28