Angular 6中如何获取EventEmitter的响应并更新父组件数据
嘿,这事儿其实挺容易搞定的,咱们一步步来:
步骤1:在父组件模板中绑定路由组件激活事件
首先,找到父组件里的<router-outlet>标签,给它加上(activate)事件绑定,这样每当路由加载子组件时,我们就能拿到子组件的实例:
<router-outlet (activate)="onComponentActivated($event)"></router-outlet>
步骤2:修改父组件的TypeScript代码,实现事件监听
接下来,在父组件的.ts文件里,我们需要:
- 导入子组件类、
Vehicle类型,还有RxJS的Subscription用来避免内存泄漏 - 实现
onComponentActivated方法,监听子组件的dataNotifier事件 - 用事件返回的结果更新父组件的
vehicles数组
示例代码如下:
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Vehicle } from '../../Models/Vehicle'; // 请根据你的项目实际路径调整 import { SearchCylinderCapacityComponent } from '../search-cylinder-capacity/search-cylinder-capacity.component'; // 路径按需调整 import { Subscription } from 'rxjs'; export class YourParentComponent implements OnInit, OnDestroy { // 替换成你的父组件类名,比如HomeComponent vehicles: Vehicle[]; private vehicleSubscription: Subscription; constructor() { } ngOnInit(): void { // 这里可以保留你原来加载初始车辆数据的逻辑 } onComponentActivated(component: any) { // 先取消之前的订阅,防止内存泄漏 if (this.vehicleSubscription) { this.vehicleSubscription.unsubscribe(); } // 判断当前激活的组件是不是我们要监听的子组件 if (component instanceof SearchCylinderCapacityComponent) { // 订阅子组件的dataNotifier事件 this.vehicleSubscription = component.dataNotifier.subscribe((filteredVehicles: Vehicle[]) => { this.vehicles = filteredVehicles; // 用筛选后的结果更新父组件的vehicles数组 }); } } ngOnDestroy(): void { // 组件销毁时务必取消订阅 if (this.vehicleSubscription) { this.vehicleSubscription.unsubscribe(); } } }
为什么这么做?
因为你的子组件是通过路由加载到<router-outlet>里的,没法像直接写在模板里的子组件那样直接绑定(dataNotifier)事件。通过(activate)事件,我们能拿到路由激活的组件实例,然后就能订阅它的EventEmitter输出了。
这样一来,当子组件调用searchVehicle()并触发dataNotifier.emit(response)时,父组件就能接收到筛选后的车辆数据,自动更新vehicles数组,页面上的表格也会跟着刷新啦!
内容的提问来源于stack exchange,提问作者monstertjie_za
相关产品推荐
相关产品推荐

