【发布时间】:2018-05-25 01:00:53
【问题描述】:
我有以下架构:
UiControlsModule
|- Component 1
|- Component 2
模块 1 在 SharedModule 中导入和导出。
CasesModule
|- CaseListComponent
|- // several other components
SharedModule 被导入 CasesModule。
现在,在 CaseListComponent 内部,我有一个组件 1(UiControlsModule 的)实例:
<cre-question-group
(valueChanged)="catchValueChange(question)">
</cre-question-group>
我正在尝试捕捉我在组件 1 中定义的值变化:
@Output() valueChanged = new EventEmitter<Question>();
someMethod(question: Question) {
this.valueChanged.emit(question);
}
方法someMethod() 被调用,并发出事件。但是,我无法在 CaseListComponent 中捕获该事件。当我检查valueChanged 时,我还可以看到上面没有订阅者(数组为空)。
我假设,这是因为它从一个模块到另一个模块,但不知道如何解决它。
非常感谢任何帮助:)
@更新: 它是否可能因为它是另一个模块的组件而不起作用?通常应该可以,还是我错了?
@更新 2:
现在我尝试使用通过主题和可观察的消息服务进行通信来实现它,但是由于某些奇迹原因,这也不起作用。 以下是我的实现方式:
question-group.component.ts:
catchValueChange(question: Question) {
this.messagesService.sendComponentChangeEvent(question);
}
messages.service.ts:
@Injectable()
export class MessagesService {
constructor() { }
// Observable string sources
private componentChangeEvent = new Subject<Question>();
// Observable string streams
componentValueChanged$ = this.componentChangeEvent.asObservable();
// Service message commands
sendComponentChangeEvent(question: Question) {
this.componentChangeEvent.next(question); // <-- breakpoint reaches this point as expected. After, nothing happens - and there's no observer on componentChangeEvent.
}
}
case-list.component.html:
ngOnInit() {
// watch for changes on edit of the components
this.subscription = this.messagesService.componentValueChanged$.subscribe( (question: any) => {
console.log(question.id + " (" + question.type + "): " + question.selection);
});
在模板中我订阅了 Observable,但它从未达到那个点。我假设错误在messages.service.ts中的某个地方? 开发控制台没有显示错误。
【问题讨论】:
-
使用
this.valueChanged.next(question);而不是this.valueChanged.emit(question); -
这也不起作用。
-
什么时候调用 someMethod?确保在组件初始化后调用它
-
另外,你有动态加载的模块吗?
-
someMethod 在输入值改变时调用,所以在初始化后调用。不,不幸的是没有动态加载模块。每个模块都导入到另一个模块的导入数组中。
标签: angular output eventemitter