【问题标题】:Broadcast data to multiple unrelated components in Angular2 through single service通过单个服务将数据广播到 Angular2 中的多个不相关组件
【发布时间】:2016-12-09 07:14:41
【问题描述】:

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

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

【问题讨论】:

    标签: javascript angular angular2-services


    【解决方案1】:

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

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

    【讨论】:

    • 我希望在我的整个应用程序中使用此服务的单个实例。即使在子模块(功能模块)下的组件中。因此,当我的 PubSubService 发出事件时,我的应用程序中的所有组件(已订阅此事件)都可以获得广播消息。
    • 上面的代码可以解决问题,在 app.module 级别注入 PubSubService,它对于所有组件/服务都是单例和静态的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 2017-12-23
    • 2014-06-02
    • 2017-11-08
    • 2017-08-23
    • 2021-07-31
    相关资源
    最近更新 更多