gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:30:59 24 4
gpt4 key购买 nike

我试图让组件通过共享服务发送消息,就像在 cookbook's 中一样“ parent 和 child 通过服务进行交流”秘诀。我有一个调用服务方法的 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})]);

关于Angular2 组件无法通过服务中的可观察对象进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35766631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com