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

Broadcast data to multiple unrelated components in Angular2 through single service

我有两个不相关的组件,它们使用一个@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 的语音相反。

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

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

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

从 service/component

发布事件
this.pubSubService.publish('event_1', "what ever message");