如何检索EvenEmitter响应Angular 6

时间:2018-05-19 20:52:02

标签: angular eventemitter angular6

我有以下父组件:

<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>的子组件。

我的子组件通过EventEmiiter发出一个事件,如下所示:

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 []可以填充事件的响应?

3 个答案:

答案 0 :(得分:1)

由于它只是一个占位符,因此无法收听loop=FALSE的事件。您可以使用“共享服务”,如本答案中所述:https://stackoverflow.com/a/41989983/5932590

要模仿router-outlet事件,共享服务可能如下所示:

dateNotifier

然后,您可以将其注入子组件并发出事件:

@Injectable()
export class DateNotifierService {
    private source = new Subject<Vehicle[]>();
    public event$ = this.source.asObservable();
    emit(eventData: Vehicle[]): void {
        this.source.next(eventData);
    }
}

将它注入您的父组件并捕获事件:

export class SearchCylinderCapacityComponent {
  vehicles: Vehicle[];

  constructor(private dateNotifier: DateNotifierService) {}

  onClick(){
    this.dateNotifier.emit(this.vehicles);
  }
}

答案 1 :(得分:1)

这个答案是基于monstertjie_za自己对这个问题的回答。

鉴于VehicleService似乎提供了获得一系列车辆的不同方式。我公开曝光vehicles

@Injectable({
    providedIn: "root"
})
export class VehicleService {
    vehicles: Vehicle[] | undefined;

    constructor(private http: HttpClient, private configService: ConfigService) { }

    searchVehiclesByCylinderCapacity(cylinderCapacity: any): void {
        var finalEndPoint = this.configService.SearchVehiclesByCylinderCapacityEndpoint 
            + cylinderCapacity;
        this.makeRequest(finalEndPoint);
    }

    searchTop10ByAirPressure(airPressure: any): void {
        var finalEndPoint = this.configService.SearchVehiclesByAirPressureEndpoint 
            + airPressure;
        this.makeRequest(finalEndPoint);
    }

    private makeRequest(endpoint: string): void {
        this.http.get<Vehicle[]>(endpoint)
            .subscribe(vehicles => this.vehicles = vehicles);
    }
}

然后子组件只启动调用,但实际上并没有做任何其他事情:

@Component({
  selector: 'app-search-engine-capacity'
})
export class SearchEngineCapacityComponent {  
  constructor(private vehicleService: VehicleService) { }

  searchVehicle(): void {
      this.vehicleService.searchVehiclesByEngineCapacity(this.engineCapacity);
  }
}

您的HomeComponent只会公开该服务,该服务会公开要在您的视图中使用的车辆:

@Component({
  selector: 'app-home',
})
export class HomeComponent implements OnInit {
  constructor(vehicleService: VehicleService) {}

  ngOnInit() {
    this.vehicleService.getAllVehicles();
  }
}
<table class="table" *ngIf="vehicleService.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 vehicleService.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>

答案 2 :(得分:0)

按照@vincecampanale的说法,这就是我想出的:

在我的VehicleService课程中,我有以下代码,用于根据不同的搜索来检索车辆。 VehicleService类还包括一个dataChangedEvent: EventEmitter<Vehicle[]>,当它被发送时,将保存Vehicle的最新结果。

这是我的VehicleService

import { Injectable, ErrorHandler, EventEmitter } from "@angular/core";
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

import { ConfigService } from "./ConfigService";
import { Vehicle } from "../Models/Vehicle";
import { HttpClient } from "@angular/common/http";
import { HttpResponse } from "selenium-webdriver/http";


@Injectable({
    providedIn: "root"
})
export class VehicleService {

    dataChangedEvent: EventEmitter<Vehicle[]> = new EventEmitter();

    constructor(private http: HttpClient, private configService: ConfigService){

    }

    SearchVehiclesByCylinderCapacity(cylinderCapacity: any): Observable<Vehicle[]> {
        var finalEndPoint = this.configService.SearchVehiclesByCylinderCapacityEndpoint + cylinderCapacity;
        return this.makeRequest(finalEndPoint);
    }
    SearchTop10ByAirPressure(airPressure: any): Observable<Vehicle[]> {
        var finalEndPoint = this.configService.SearchVehiclesByAirPressureEndpoint + airPressure;
        return this.makeRequest(finalEndPoint);
    }

    private makeRequest(endpoint: string): Observable<Vehicle[]> {
        return this.http.get<Vehicle[]>(endpoint);
    }
}

每个子组件一旦在dataChangedEvent处理程序中收到响应,就会将数据发送到K中的subscribe()

这是一个子组件:

import { Component, OnInit } from '@angular/core';
import { VehicleService } from '../../Services/VehicleService';

@Component({
  selector: 'app-search-engine-capacity',
  templateUrl: './search-engine-capacity.component.html',
  styleUrls: ['./search-engine-capacity.component.css']
})
export class SearchEngineCapacityComponent implements OnInit {

  engineCapacity: any;

  constructor(private vehicleService: VehicleService) { 

  }

  ngOnInit() {
  }

  searchVehicle(): void {
    this.vehicleService
          .SearchVehiclesByEngineCapacity(this.engineCapacity)
            .subscribe(response => this.vehicleService.dataChangedEvent.emit(response));
  }
}

最后,在父组件中,我subscribe()dataChangedEvent中的VehicleService,并且当搜索到的车辆的数据发生变化时,将通知父组件。 以下是我的父组件,该dataChangedEvent

内的VehicleService中的constructor
import { Component, OnInit, Input } from '@angular/core';
import { VehicleService } from '../../Services/VehicleService';
import { Vehicle } from '../../Models/Vehicle';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  vehicles: Vehicle[];

  constructor(private vehicleService: VehicleService) {
    this.vehicleService.dataChangedEvent.subscribe(response => this.vehicles = response)
   }

  ngOnInit() {
    this.vehicleService
      .GetAllVehicles()
        .subscribe(response => this.vehicles = response, 
                    error => console.log(error));
  }

  populateGrid(vehicleData: Vehicle[]){
    this.vehicles = vehicleData;
  }
}