gpt4 book ai didi

typescript - Angular 2 : Cannot subscribe to custom events emitted from shared service

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

我已经开始学习 Angular2,但在使用发射/订阅的自定义事件方面遇到了问题。

我创建了一个小演示来演示:Plunker

如您所见,有一个 PreviewService 类。这个类有一个 setURL(url: string) 方法,如果被调用,它会发出一个 contentUrlChange$ 事件。

src/services/preview.service.ts

import {Injectable, EventEmitter} from 'angular2/core';

@Injectable()
export class PreviewService {

private _url: string;

contentUrlChange$: EventEmitter<any>;

constructor() {
this.contentUrlChange$ = new EventEmitter;
};

setURL(url: string): void {
this._url = url;
this.contentUrlChange$.emit(url);
};

}

在 App 组件的构造函数中,我订阅了 PreviewService 的 contentUrlChange$ 事件。如果您运行 Plunker,您将看到警报窗口。

src/app.ts

[...]
constructor(private _previewService: PreviewService) {
_previewService.contentUrlChange$.subscribe(url => {
alert("APP " + url);
})

_previewService.setURL('http://www.example.com');
};
[...]

但这是我的问题:我有另一个组件 PreviewComponent,在该组件的构造函数中,就像在 App 组件的构造函数中一样,我订阅了 PreviewService 的 contentUrlChange$ 事件。但奇怪的是,应该出现的警告窗口并没有出现。

src/component/preview.component.ts

constructor(private _previewService: PreviewService) {
_previewService.contentUrlChange$.subscribe(url => {
alert("PREVIEW " + url); // Nothing happens here
})
};

我通读了几个问题/答案,这表明我正在做的事情应该有效,但仍然没有成功。任何想法/解决方案将不胜感激。谢谢。

最佳答案

您的笨拙几乎没有问题。首先,如果您向组件注入(inject)单独的服务实例,它们将无法订阅相同的事件,原因很简单,因为它们是不同的变量(属性)。因此,您必须为每个组件提供相同的服务,只需在应用程序的 Bootstrap 中执行:

bootstrap(App, [
YourService
]).catch(...)

其次,当子组件 (PreviewComponent) 尚未初始化时,您正在从应用程序组件发出值。要等待,您可以使用 setTimeout(func, 0)(但这是 hack,我不推荐这样做),或者简单地使用内置的 angular 的 OnInit 生命周期钩子(Hook)

import {OnInit} from 'angular2/core';

...


ngOnInit() {
// emit values here
}

这是更新的插件:http://plnkr.co/edit/okiNPFRKKYXfce1P0D5o

关于typescript - Angular 2 : Cannot subscribe to custom events emitted from shared service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34978455/

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