【问题标题】:Event not caught when fired from rxJs subscribe onComplete callback从 rxJs 订阅 onComplete 回调触发时未捕获事件
【发布时间】:2019-09-24 21:51:24
【问题描述】:

我从 http 请求中接收到一些数据,我想通过 @Output 和 EventEmitter 将这些数据中继到父组件。我的目标是在子组件中新建一个item,在后端成功存储后,追加一个在后端创建的Id,追加到frontEnd中的item,最后添加到父view。

我尝试从 .finally() 回调和 .onComplete() 内部调用 this.newItem.emit(item) ,以及我们onNext()。在所有情况下,事件都没有在父组件中被捕获,除了我在 .subscribe() 块之后发出项目

child.ts
/* */
@Output() newItemEmitter= new EventEmitter();
/* */
saveItem() {
 let itemToView: {
  ... // A lot of data   
 };
 this.itemService.saveItem(item).subscribe(result => {
    itemToView = {
     ...
     Id: result.Data
    }
   }, error => {console.log(error)}
   , () => { console.log('Emitting!'); this.newItemEmitter.emit(itemToView) }
 }
 this.closeView() // Was not originally included. (1)
}
// this.newItemEmitter.emit(itemToView) // If emitting from  
// here, itemToView will not contain the right Id from the backend.

我故意省略了一些不相关的html。

parent.html
<ng-template  let-c="close" let-d="dismiss">
  <fixed-item  (newItemEmitter)="addNewItemToView($event)" (closed)="closeAddNewItemTemplateView()">
  </fixed-item>
</ng-template>
parent.ts
addNewItemToView($event) {
    console.log('Received event from child: ', $event)
    // Add to view here
}

我的预期输出是 Emitting!,然后是 Received event from child,但到目前为止,唯一的输出是 Emitting!。 p>

编辑: (1):删除 this.closeView() 解决了我的问题。我认为问题在于事件在 ng-template 关闭时被中止。

【问题讨论】:

  • 确保从“@angular/core”导入事件发射器类。
  • 它是进口的。如果有什么不同,我会使用 Angular 5。
  • 好的,我认为“itemToView”不在它发出的函数范围内。
  • 更改为全局范围 this.itemToView 没有区别 :(
  • 只是我的好奇心,你试过用Rxjs/Subject代替EventEmitter吗?

标签: angular rxjs eventemitter angular-event-emitter


【解决方案1】:

我的问题是当我调用 this.closeView() 来关闭组件时。我现在没有从子组件本身关闭子组件,而是从父组件调用 destroy 方法。我相信调用 this.closeView() 会以某种方式从事件循环中删除发出的事件,如果事件的源在 subscribe 回调中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    相关资源
    最近更新 更多