[英]Angular2/4 - Creating an array of data to share across multiple components via service
[英]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则相反。
如果我错误地使用了发射器,有人可以建议如何获得此功能。 我的组件没有任何(父/子)关系。 一个人可以是另一个人的祖父母的兄弟姐妹。
首先创建一个全球发布订阅服务
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.