Angular 2-使用RXJS Observables [英] Angular 2 - Using RXJS Observables

查看:55
本文介绍了Angular 2-使用RXJS Observables的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following jsfiddle in Angular 1 which has two components, boxA, boxB that listens to a RXJS subject called msgSubject defined in msgService.

mainCtrl通过msgService广播功能广播消息.如果boxA和boxB订阅了msgSubject(可以取消订阅),则更新后的消息将显示在每个组件视图中.

The mainCtrl broadcast a message through msgService broadcast function. If boxA and boxB are subscribed to the msgSubject (there is an option to unsubscribe) the updated message will show in each respective component view.

角度1可观察到的Js蹒跚

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

My question is how do I replicate this in Angular 2? I've googled and most of the tutorials relate to HTTP and asynchronous search. I appreciate if someone can at least tell me the syntax to setup the subject, broadcast and subscribe. Any help I am so grateful for. Thanks in advance.

Angular 1代码

Angular 1 Code

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

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);
        }
    }   
}])

推荐答案

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

You could use a service to communicate between the two components:

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);
  }
}

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

Then in one components send a broadcast message:

BroadcastService.announceBoradcast("Hello World");

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

Then other component can subscribe to the broadcast:

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

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

Here is some more information on communication between components in Angular2: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

这篇关于Angular 2-使用RXJS Observables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆