AngularJS 1.5+ Components do not support Watchers, what is the work around?

前端 未结 7 1292
广开言路
广开言路 2020-11-22 09:23

I\'ve been upgrading my custom directives to the new component architecture. I\'ve read that components do not support watchers. Is this correct? If so how do you detect cha

7条回答
  •  孤独总比滥情好
    2020-11-22 09:53

    To anyone interested in my solution, I end up resorting to RXJS Observables, which what you will have to use when you get to Angular 2. Here is a working fiddle for communications between components, it gives me more control on what to watch.

    JS FIDDLE RXJS Observables

    class BoxCtrl {
        constructor(msgService) {
        this.msgService = msgService
        this.msg = ''
    
        this.subscription = msgService.subscribe((obj) => {
          console.log('Subscribed')
          this.msg = obj
        })
        }
    
      unsubscribe() {
        console.log('Unsubscribed')
        msgService.usubscribe(this.subscription)
      }
    }
    
    var app = angular
      .module('app', ['ngMaterial'])
      .controller('MainCtrl', ($scope, msgService) => {
        $scope.name = "Observer App Example";
        $scope.msg = 'Message';
        $scope.broadcast = function() {
          msgService.broadcast($scope.msg);
        }
      })
      .component("box", {
        bindings: {},
        controller: 'BoxCtrl',
        template: `Listener: 
    {{$ctrl.msg}}
    Unsubscribe A` }) .factory('msgService', ['$http', function($http) { var subject$ = new Rx.ReplaySubject(); return { subscribe: function(subscription) { return subject$.subscribe(subscription); }, usubscribe: function(subscription) { subscription.dispose(); }, broadcast: function(msg) { console.log('success'); subject$.onNext(msg); } } }])

提交回复
热议问题