2
我试图让组件通过共享服务发送消息,如cookbook's“父级和子级通过服务通信”配方。我有一个Sender
组件,它调用一个服务的方法,在该方法中触发一个事件。还有一个Receiver
组件,它只是监听事件。Angular2组件无法通过服务中的可观察项进行通信
问题是Receiver
没有得到一个事件。下面的代码:
import {bootstrap} from 'angular2/platform/browser'
import {Injectable, Component} from 'angular2/core';
import 'rxjs/Rx';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class TestService {
private _subject = new Subject<any>();
event$ = this._subject.asObservable();
doFoo() {
console.log('Doing foo hard...')
this._subject.next('hey');
}
}
@Component({
selector: 'receiver-component',
template: 'Value is {{ value }}',
providers: [
TestService
],
})
export class ReceiverComponent {
private value: number = 'nope';
constructor(private service: TestService) {
this.service.event$.subscribe(data => this.value = data)
}
}
@Component({
selector: 'sender-component',
template: '<button (click)="fireEvent()">Click me</button>',
providers: [
TestService
],
})
export class SenderComponent {
constructor (private service: TestService) {}
fireEvent() {
this.service.doFoo()
}
}
bootstrap(SenderComponent);
bootstrap(ReceiverComponent);
当我按一下按钮,我看到TestService.doFoo()
调试消息,所以它得到执行。但事件消息只是没有通过。为什么?
更新:我正在使用[email protected]
和[email protected].0.0-beta.2
。
Günter,非常感谢!您可能需要在示例中导入'provide',以使其完全可行。 –
感谢您的反馈 - 修正。 –
这里的工作示例 https://plnkr.co/edit/OIFaAsLbb4AWndTo7tOv?p=preview – Sudhakar