RxJs and Angular1 - how to avoid $ scope?

Pseudocode for angular 1.5 component with RxJs:

component('demo', {
  template: `<div>
            <div ng-if="verificationFailed">Sorry, failed to verify</div>
            <button ng-if="continueEnabled">Continue</button>
            <button ng-click="verify()">Verify</button>
            </div>`,
  controllerAs: 'ctrl',
  bindings: {
    someOptions: '='
  },
  controller: ($scope, someService) => {
    var ctrl = this;

    ctrl.continueEnabled = false;

    ctrl.verificationFailed = false;

    ctrl.verify = function() {
      Rx
      .Observable
      .interval(10 * 1000)
      .timeout(2 * 60 * 1000)
      .flatMapLatest(_ => { someService.verify(ctrl.someOptions.id)})
      .retry(1)
      .filter((result) => { result.completed })
      .take(1)
      .subscribe(_ => {
        $scope.$evalAsync(_ => {
          ctrl.continueEnabled = true
        });
      }, _ => {
        $scope.$evalAsync(() => {
          ctrl.verificationFailed = true;
        });
      });
    };
  }
});

How to avoid using $ scope with $ evalAsync to trigger a digest? Without it, the view simply does not update.
What for? Since $ scope does not exist in angular2, and I want to make the migration as simple as possible.

+4
source share
1 answer

You can use angular 1-asynchronous filter. Take a look at this good article: http://cvuorinen.net/2016/05/using-rxjs-observables-with-angularjs-1/

Here is an example:

(function(angular) {
  var myComponent = (function () {
    function myComponent() {
      this.template = "<div><br/> Time: {{ctrl.time | async:this}}</div>";
      this.controllerAs = 'ctrl';
      this.controller = "myController";
    }
    return myComponent;
  }());

  var myController = (function() {
    function myController() {
      this.time = Rx.Observable.interval(1000).take(50);
    }
    return myController;
  }());

  angular.module('myApp', ['asyncFilter']);
  angular.module('myApp').component('myComponent', new myComponent());
  angular.module('myApp').controller('myController', myController);
})(window.angular);

See how Plunker works: https://plnkr.co/edit/80S3AG?p=preview

+5
source

All Articles