【问题标题】:Output() not emitting event输出()不发出事件
【发布时间】: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


【解决方案1】:

模板事件处理函数中的参数必须称为$event。您可以在处理程序方法声明中(在组件类定义中)随意调用它。

试试这样:

template.html

<cre-question-group (valueChanged)="catchValueChange($event)"></cre-question-group>

(代替)

<cre-question-group
    (valueChanged)="catchValueChange(question)">
</cre-question-group>

打字稿

catchValueChange(question: Question) {
    console.log('question', question);
}

【讨论】:

  • 我可以知道哪个是父组件和子组件你能在这个问题中分享吗
  • 发射功能只适用于子到父的方式,而不是父到子的方式
  • 所以从CaseListComponent调用cre-question-group(QuestionGroupComponent)。所以没有真正的父子关系,因为它们在单独的模块中。
猜你喜欢
  • 2019-04-15
  • 2016-11-20
  • 2021-07-04
  • 2014-08-28
  • 1970-01-01
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
  • 2012-10-18
相关资源
最近更新 更多