AngularJs – RXJS Observable取消订阅
发布时间:2020-12-17 07:34:41 所属栏目:安全 来源:网络整理
导读:我已经设置了一个RXJS可观察.我有两个组件订阅服务工厂的主题.如何取消订阅所选组件到主题以便按下按钮它会停止收听主题广播? 看我的jsfiddle Unsubscribe App 我的代码: div ng-app="myApp" ng-controller="mainCtrl" script type="text/ng-template" id=
我已经设置了一个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; }); 然后,您可以在取消订阅时调用订阅上的dispose方法: boxA.unsubscribe = function(){ console.log('Unsubscribe A'); boxASubscription.dispose(); }; 注: 出于某种原因,我无法让您的演示与< md-button>一起使用所以我将其更改为< button>为了演示. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |