我已经设置了一个RXJS可观察.我有两个组件订阅服务工厂的主题.如何取消订阅所选组件到主题以便按下按钮它会停止收听主题广播?
看我的jsfiddle Unsubscribe App
我的代码:
<div ng-app="myApp" ng-controller="mainCtrl"> <script type="text/ng-template" id="/Boxa"> BoxA - Message Listener: </br> <strong>{{BoxA.msg}}</strong></br> <md-button ng-click='BoxA.unsubcribe()' class='md-warn'>Unsubscribe A</md-button> </script> <script type="text/ng-template" id="/Boxb"> BoxB - Message Listener: </br> <strong>{{BoxB.msg}}</strong></br> <md-button ng-click='BoxB.unsubcribe()' class='md-warn'>Unsubscribe B</md-button> </script> <md-content class='md-padding'> <h3> {{name}} </h3> <label>Enter Text To Broadcast</label> <input ng-model='msg'/></br> <md-button class='md-primary' ng-click='broadcastFn()'>Broadcast</md-button></br> <h4> Components </h4> <Box-a></Box-a></br> <Box-b></Box-b> </md-content> </div><!--end app--> var app = angular.module('myApp',['ngMaterial']); app.controller('mainCtrl',function($scope,msgService) { $scope.name = "Observer App Example"; $scope.msg = 'Message'; $scope.broadcastFn = function(){ msgService.broadcast($scope.msg); } }); app.component("BoxA",{ bindings: {},controller: function(msgService) { var BoxA = this; BoxA.msgService = msgService; BoxA.msg = ''; BoxA.msgService.subscribe(function(obj) { console.log('Listerner A'); BoxA.msg = obj; }); BoxA.unsubscribe=function(){ }; },controllerAs: 'BoxA',templateUrl: "/Boxa" }) app.component("BoxB",controller: function(msgService) { var BoxB = this; BoxB.msgService = msgService; BoxB.msg = ''; BoxB.msgService.subscribe(function(obj) { console.log('Listerner B'); BoxB.msg = obj; }); BoxB.unsubscribe=function(){ }; },controllerAs: 'BoxB',templateUrl: "/Boxb" }) app.factory('msgService',['$http',function($http){ var msgSubject = new Rx.ReplaySubject(); return{ subscribe:function(subscription){ msgSubject.subscribe(subscription); },broadcast:function(msg){ console.log('success'); msgSubject.onNext(msg); } } }])
请参阅更新的小提琴:
here
subscribe函数返回一个Disposable来使用,你必须首先从你的工厂返回订阅(第60行):
subscribe: function(subscription){ return msgSubject.subscribe(subscription); }
这将允许您将订阅存储在每个控制器中以便将来使用. (第21和第42行)
var BoxASubscription = BoxA.msgService.subscribe(function(obj) { console.log('Listerner A'); BoxA.msg = obj; });
BoxA.unsubscribe = function(){ console.log('Unsubscribe A'); BoxASubscription.dispose(); };
注:
出于某种原因,我无法让您的演示与< md-button>一起使用所以我将其更改为< button>为了演示.