【发布时间】:2023-04-01 16:16:01
【问题描述】:
我有以下父组件:
<h1>Vehicle Inventory</h1>
<p *ngIf="!vehicles"><em>No vehicle entries found</em></p>
<div *ngIf="vehicles">
<ul class="nav nav-pills nav-fill">
<li class="nav-item">
<a class="nav-link" routerLink="/home/price" routerLinkActive="active">Search By price</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="/home/make-model" routerLinkActive="active">Search By Make Or Model</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="/home/engine-capacity" routerLinkActive="active">Search By Engine Capacity</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="/home/cylinder-variant" routerLinkActive="active">Search By Cylinder Variant</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="/home/cylinder-capacity" routerLinkActive="active">Search By Cylinder Capacity</a>
</li>
</ul>
<router-outlet></router-outlet>
</div>
<table class="table" *ngIf="vehicles">
<thead class="thead-dark">
<tr>
<th scope="col">Make</th>
<th scope="col">Model</th>
<th scope="col">Engine Capacity</th>
<th scope="col">Cylinder Variant</th>
<th scope="col">Top Speed</th>
<th scope="col">Price (R)</th>
<th scope="col">Cylinder Capacity</th>
<th scope="col">Air Pressure/second</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let vehicle of vehicles">
<td>{{ vehicle.Make }}</td>
<td>{{ vehicle.Model }}</td>
<td>{{ vehicle.EngineCapacity }}</td>
<td>{{ vehicle.CylinderVariant }}</td>
<td>{{ vehicle.TopSpeed }}</td>
<td>{{ vehicle.Price }}</td>
<td>{{ vehicle.IndividualCylinderCapacity }}</td>
<td>{{ vehicle.AirPressurePerSecond }}</td>
</tr>
</tbody>
</table>
从上面可以看出,我这里有一些导航,会决定子组件被加载到<router-outlet>中。
我的子组件通过EventEmitter 发出一个事件,如下所示:
import { Component, OnInit, Input, Output } from '@angular/core';
import { VehicleService } from '../../Services/VehicleService';
import { EventEmitter } from '@angular/core';
import { Vehicle } from '../../Models/Vehicle';
@Component({
selector: 'app-search-cylinder-capacity',
templateUrl: './search-cylinder-capacity.component.html',
styleUrls: ['./search-cylinder-capacity.component.css']
})
export class SearchCylinderCapacityComponent implements OnInit {
@Input() cylinderCapacity: any;
@Output() dataNotifier: EventEmitter<Vehicle[]> = new EventEmitter();
constructor(private service: VehicleService) { }
ngOnInit() {
}
searchVehicle() {
this.service
.SearchVehiclesByCylinderCapacity(this.cylinderCapacity)
.subscribe(response => this.dataNotifier.emit(response));
}
}
如何捕获此事件的响应,以便我的父组件的车辆:Vehicle[] 可以填充事件的响应?
【问题讨论】:
-
我不会为这种行为引入 vincecampanale 所描述的额外服务。您已经有一个应该可用的
VehicleService。您如何使用SearchVehiclesByCylinderCapacity发出的数据? -
@DavidWalschots 我认为 vincecampanale 意味着我应该使用我现有的服务。他只是以 DateNotifierService 为例。我将它实现到我的服务中
-
我仍然对您的使用感兴趣。您可能不需要这些事件。
-
@DavidWalschots 添加了一个 aswer,所以你可以看到我是如何实现的
标签: angular eventemitter angular6