Angular 2 - 使用RXJS Observables

时间:2016-09-29 05:36:11

标签: angular rxjs

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

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

Angular 1 Observable Js Fddile

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

Angular 1 Code

HTML

lazy var realm = try! Realm(configuration:Realm.Configuration(deleteRealmIfMigrationNeeded: true))

的Javascript

<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-->

1 个答案:

答案 0 :(得分: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

相关问题