【发布时间】: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