AngularJS clause is not resolved multiple times using $ interval

I am surprised to understand why the promise of angularjs is not resolved multiple times using the $interval service. Below is my code. Variable i increased several times, however, a promise is only allowed once.

 var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope, myService) { myService.then(function(result) { $scope.i = result; }); }); app.factory('myService', function($interval, $q) { var deferred = $q.defer(); var i = 0; $interval(function() { i += 1; deferred.resolve(i); }, 2000); return deferred.promise; }); 

Plunker

+5
source share
2 answers

Using AngularJS, you can use the $ q notification function ( https://docs.angularjs.org/api/ng/service/ $ q) instead of permission:

 var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope, myService) { // Notice that the third callback is for notify myService.then(null, null, function(result) { $scope.i = result; }); }); app.factory('myService', function($interval, $q) { var deferred = $q.defer(); var i = 0; $interval(function() { i += 1; deferred.notify(i); }, 2000); return deferred.promise; }); 

You might want to add $ interval.cancel () to stop the loop at some point / condition ( https://docs.angularjs.org/api/ng/service/ $ interval).

+4
source

A promise is one deferred value. It will not be allowed more than once.

If you need similar functionality for event streams, select Rx.JS

With Rx, your code would look something like this:

 var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope, myService) { myService.subscribe(function(result) { $scope.i = result; }); }); app.factory('myService', function($interval, $q) { var subject = new Rx.Subject(); var i = 0; $interval(function() { i += 1; subject.onNext(i); }, 2000); return subject; }); 
+5
source

Source: https://habr.com/ru/post/1203858/


All Articles