Angular2 组件无法通过服务中的可观察对象进行通信

Angular2 components fail to communicate via observable in a service

我正在尝试让组件通过共享服务发送消息,就像在 cookbook's "Parent and children communicate via a service" 食谱中一样。我有一个调用服务方法的 Sender 组件,在该方法中触发了一个事件。还有一个 Receiver 组件,它只是监听事件。

问题是 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() 的调试消息,所以它被执行了。但是事件消息并没有被传递。为什么?

更新:我正在使用 angular2@2.0.0-beta.7rxjs@5.0.0-beta.2

这不是共享服务。每个组件都有自己的实例。

如果您将服务添加到组件的 providers 列表中,每个组件将获得一个新实例。

如果您 运行 bootstrap() 两次,您将创建两个不同的 Angular 应用程序,它们不共享任何内容。请参阅代码的最后几行如何建立连接:

import {bootstrap} from 'angular2/platform/browser'
import {Injectable, Component, provide} 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()
    }
}

sharedService = new TestService();
bootstrap(SenderComponent, [provide(TestService, {useValue: sharedService})]);
bootstrap(ReceiverComponent, [provide(TestService, {useValue: sharedService})]);