【问题标题】:Angular 2 - Using RXJS ObservablesAngular 2 - 使用 RXJS Observables
【发布时间】:2016-09-29 05:36:11
【问题描述】:

我在 Angular 1 中有以下 jsfiddle,它有两个组件 boxA、boxB,它们侦听在 msgService 中定义的名为 msgSubject 的 RXJS 主题。

mainCtrl 通过 msgService 广播功能广播消息。如果 boxA 和 boxB 订阅了 msgSubject(有一个取消订阅的选项),更新的消息将显示在每个相应的组件视图中。

Angular 1 Observable Js Fddile

我的问题是如何在 Angular 2 中复制它?我用谷歌搜索过,大部分教程都与 HTTP 和异步搜索有关。如果有人至少可以告诉我设置主题、广播和订阅的语法,我将不胜感激。我非常感谢任何帮助。提前致谢。

Angular 1 代码

HTML

<div ng-app="myApp" ng-controller="mainCtrl">
  <style>

  .table-cell{
    border-right:1px solid black;
  }
  </style>
  <script type="text/ng-template" id="/boxa">
  BoxA - Message Listener: </br>
  <strong>{{boxA.msg}}</strong></br>
  <button ng-click="boxA.unsubscribe()">Unsubscribe A</button>
  </script>
  <script type="text/ng-template" id="/boxb">
    BoxB - Message Listener: </br>
  <strong>{{boxB.msg}}</strong></br>
  <button ng-click="boxB.unsubscribe()">Unsubscribe B</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-->

Javascript

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 = '';

        var boxASubscription = boxA.msgService.subscribe(function(obj) { 
            console.log('Listerner A');
          boxA.msg = obj;
                });

        boxA.unsubscribe = function(){
            console.log('Unsubscribe A');
            boxASubscription.dispose();
        };

      },
      controllerAs: 'boxA',
      templateUrl: "/boxa"
})
app.component("boxB",  {
      bindings: {},
      controller: function(msgService) {
        var boxB = this;
        boxB.msgService = msgService;

        boxB.msg = '';
        var boxBSubscription = boxB.msgService.subscribe(function(obj) { 
            console.log('Listerner B');
          boxB.msg = obj;
                });

        boxB.unsubscribe=function(){
            console.log('Unsubscribe B');
          boxBSubscription.dispose();
        };
      },
      controllerAs: 'boxB',
      templateUrl: "/boxb"
})

app.factory('msgService', ['$http', function($http){
    var msgSubject = new Rx.Subject();
    return{
        subscribe:function(subscription){
            return msgSubject.subscribe(subscription);
        },
        broadcast:function(msg){
        console.log('success');
            msgSubject.onNext(msg);
        }
    }   
}])

【问题讨论】:

标签: angular rxjs


【解决方案1】:

您可以使用服务在两个组件之间进行通信:

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';
@Injectable()
export class BroadcastService {

  private broadcastSource = new Subject<string>();

  // Observable string streams
  // Return as observale to encapsulate the subject
  broadcastAnnounce$ = this.broadcastSource.asObservable();

  // Service message commands
  announceBoradcast(message: string) {
    this.broadcastSource.next(message);
  }
}

然后在一个组件中发送一个广播消息:

BroadcastService.announceBoradcast("Hello World");

然后其他组件可以订阅广播:

BroadcastService.broadcastAnnounce$.subscribe((message) => {
    console.log(message);
})

这里有更多关于 Angular2 中组件之间通信的信息: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

【讨论】:

  • 谢谢,这看起来和我想要的完全一样,会试一试然后回来。 Also.noob 问题 $ 和 是什么意思?
  • 它只是表明它是一个可观察的流:)
  • 很高兴听到:)
  • @DNRN 为什么不直接使用 broadcastSource.subscribe() 而不创建 broadcastAnnounce$
猜你喜欢
  • 2017-03-20
  • 2016-09-07
  • 2020-02-10
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 2017-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多