通过单一服务将数据广播到Angular2中的多个不相关组件

时间:2016-12-09 07:14:41

标签: javascript angular angular2-services

我有两个不相关的组件,它们使用一个@injectable服务。

调用特定服务方法时。它发出一个均匀的。第二个组件订阅了该事件。

我的代码如下:

组件Bot2:

import { Component, OnInit, NgZone, EventEmitter} from '@angular/core';
import { SpeechEngine} from '../../services/common/Speechengine';

@Component({
  selector: 'bot2',
  template: '<h3>bot2</h3> <input type="button" value="Emmit" (click)="testEmmiter()"/>',
  providers: [],

 })
 export class Bot2 {
   _speechEngine: any
   constructor(private zone: NgZone) {
    this._speechEngine = new SpeechEngine(this.zone);
    this._speechEngine.BotActivation$.subscribe(obj => { this.AutoBotActivation(obj.speechActive) })
 }
 testEmmiter() {
    this._speechEngine.testEmiter();
 }
 AutoBotActivation(speechActive) {
    alert(" Bot2 subscribed function called.")
 }
}

@Component({
  selector: 'bot3',
  template: '<h3>bot3</h3> <input type="button" value="Emmit" (click)="testEmmiter()"/>',
  providers: [],

})
export class Bot3 {
   _speechEngine: any
   constructor(private zone: NgZone) {
     this._speechEngine = new SpeechEngine(this.zone);
     this._speechEngine.BotActivation$.subscribe(obj => { this.AutoBotActivation(obj.speechActive) })
 }
 testEmmiter() {
    this._speechEngine.testEmiter();
 }
 AutoBotActivation(speechActive) {
    alert(" Bot3 subscribed function called.")
 }
}

服务:

@Injectable()
export class SpeechEngine{
  BotActivation$: EventEmitter<any> = new EventEmitter<any>()    
  constructor(private zone: NgZone) {  }
  testEmiter() {
    this.BotActivation$.next({
        speechActive: false
    });
  }

}   

我的服务已添加到appModule Providers。     提供者:[SpeechEngine]

问题是当我从bot2调用testEmmiter()时,服务发出函数并且bot2中的订阅捕获它。但是bot3没有捕获。与bot3相反。

如果我错误地使用发射器,有人可以建议如何获得此功能。我的组件没有任何(父/子)关系。一个人可以是其他人的盛大父母的兄弟姐妹。

1 个答案:

答案 0 :(得分:0)

首先创建一个全局发布订阅服务

import { Injectable, EventEmitter } from '@angular/core';

@Injectable()
export class PubSubService {
  emitter: EventEmitter<any> = new EventEmitter();

  constructor( ) { }

  subscribe(callback) {
    return this.emitter.subscribe(callback);
  }

  publish(event, data?) {
    let payload = {
      type: event,
      data: data
    };
    this.emitter.emit(payload);
  }

}

订阅您的组件(任何组件)

constructor( private pubSubService: PubSubService) { }

ngOnInit() {
  this.pubSubService.subscribe(event => {
    if (event.type === 'event_1') {
      // do something
    } else if (event.type === 'event_2') {
      // do something
    }
  });
}

从服务/组件发布事件

this.pubSubService.publish('event_1', "what ever message");