【问题标题】:Angular 12: Listening to multiple children events in Parent componentAngular 12:在父组件中监听多个子事件
【发布时间】:2021-11-02 08:59:16
【问题描述】:

在事件等方面,我是 Angular 的初学者。

最近我一直在做这个项目,我有一个名为 Layout 的父组件,它包含多个子组件,这些子组件应该通过各种 服务 进行 CRUD 操作.

现在 Layout 组件有一个导航栏,这个导航栏显示我的库存中每个类别的物品数量。

目标:当我在其中一个子组件中发出添加或删除请求时,父组件应该向后端发起请求。这样它将从数据库中检索新的项目数

问题:我不知道我应该在这里使用正确的方法,我知道我需要监听来自每个子组件的事件,但我不知道如何。

我应该监听组件还是订阅每个服务并等待它发出事件?

最好的方法是什么?

我的代码很长,所以我将添加一些片段来说明我在做什么:

Layout.component.ts

 ngOnInit(): void {
        this.prepareNavbar()
    }

Layout.component.html

<nav> 
<!-- Here I display the numbers of each item retrieved from the database -->
</nav>
<router-outlet></router-outlet>

AddItem1.component.ts

addItem(){
this.Categorie1Service.addItem.subscribe()
}

删除Item.component.ts

DeleteItem(){
this.Categorie2Service.DeletItem.subscribe()
}

【问题讨论】:

  • 您正在寻找 @Output() 装饰器,请参阅本指南:angular.io/guide/…
  • 嗨,我阅读了文档,但我不明白的是,这些示例在 @Component({ template: ...}) 中包含子项,而我没有
  • router-outlet 在这里真的相关吗?您想要对其事件做出反应的项目在哪里?在nav?
  • 我认为是相关的,因为我没有模板,而是 layout.html 在 中显示了路由器使用的组件,我最终在我的父母之间使用了一项服务和孩子

标签: javascript angular typescript rxjs eventemitter


【解决方案1】:

使用共享数据服务

您可以在您的应用程序上共享一个数据服务,您已经知道了这一点。如果您想在应用程序的其他地方使用共享数据,这是一个不错的选择。

使用 onActivate

在 child.component.ts 中:


@Output() deleteEvent = new EventEmitter
@Output() addEvent = new EventEmitter

deleteItem(id){
    this.deleteEvent.emit(id)
}
addItem(data) {
    this.deleteEvent.emit(data)
}

在父模板中:

<router-outlet (activate)="onActivate($event)"></router-outlet>

在 parent.component.ts 中:

onActivate(componentReference) {
   componentReference.deleteEvent.subscribe((id) => {
      // implementation
   });
   
   componentReference.addEvent.subscribe((data) => {
      // implementation 
   })
}

【讨论】:

  • 对不起,我不明白应该把 标签放在哪里,我的父组件已经有十几个子组件
  • 问题是,您不能将(someEvent) 放在router-outlet 上,它需要继续作为路由添加到其位置的组件。
  • 我了解,我做了一些研究,结果发现 (someEvent) 不适用于我的情况。我最终创建了一个带有 behaviousSubject 的服务和一个发出它的方法,之后我从我的组件中调用了该方法并且它起作用了。
猜你喜欢
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 2017-07-09
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
相关资源
最近更新 更多