将嵌套组件孙子之间的事件发送到根组件

问题描述 投票:2回答:1

我有wheels.component嵌套到car.component

wheels.component:

export class WheelsComponent {    
    @Output() onLoaded : EventEmitter<string>() = new EventEmitter<string>();

    private downloadAllFiles(url: string) {
        this.onLoaded.emit('Hello, World 1!');
        //some operations to wait
        this.onLoaded.emit('Hello, World 2!');

    };
}

组件car.component不是在html页面写的,而是通过car-routing.module.ts中的路由调用:

@NgModule({
    imports: [
        RouterModule.forChild([
            {
                path: 'sfactmessage/:id',
                component: CarComponent,
                resolve: {
                    card: cardResolver
                }
            }
        ])
    ],
    exports: [RouterModule]
})
export class CarRoutingModule {}

我想要的是处理从wheels.component发出的事件,而不是在car.component,而是在app.component。

是否有可能在app.component处理事件?

qazxsw poi(对不起,这是我的第一个plunker示例),但是给出了我的应用程序如何安排的视图。

javascript angular
1个回答
9
投票

你好朋友。

所以基本上如果你想在你的应用程序中全局使用事件,你可以使用The plunker sample is not workingService结合使用

在这种情况下,您可以创建一个服务,例如car.service.ts

EventEmitter

然后在子组件中使用此服务来发出类似wheel.component.ts的事件

import { Injectable, EventEmitter } from '@angular/core';
@Injectable()
export class CarService {
  onLoaded : EventEmitter<string> = new EventEmitter<string>();
}

然后从AppComponent捕获此事件,例如app.component.ts

import { Component, EventEmitter } from '@angular/core';
import { CarService }  from './car.service';
@Component({
    selector: 'wheels',
    template: '<a (click)="sendValues()"> Click me to send value </a>'
})
export class WheelsComponent {

    constructor(private carService:CarService ){}

    sendValues() {
       /* Use service to emit events that can be used everywhere in the application */
        this.carService.onLoaded.emit('Button in WheelsComponent was clicked ...');
    }; 
}

重要______________

如果您希望您的服务全局工作,您需要在顶级提供程序中声明它,例如app.module.ts是一个好地方:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { CarService }  from './cars/car.service';
import { Subscription }  from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: `src/app.component.html`
})
export class AppComponent implements OnInit, OnDestroy{ 
  private subscription: Subscription;
  private loading = true;
  name = 'Angular'; 

  constructor(private carService: CarService){} 

  ngOnInit(){
    this.subscription = this.carService.onLoaded.subscribe((message) => {

      /*
        Here you receive events from anywhere where
        carService.onLoaded.emit() is used
      **/

        alert(`From AppComponent -> ${message}`);
    });
  } 

  ngOnDestroy(){
    /* Don't forget to unsubscribe when component is destroyed */
    this.subscription.unsubscribe();
  }
}

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { CarComponent} from './cars/car.component'; import { WheelsComponent} from './cars/wheels.component'; import { HomeComponent} from './home.component'; import { routing } from './app.routing'; import { CarService } from './cars/car.service'; @NgModule({ imports: [ BrowserModule, FormsModule, routing ], declarations: [ AppComponent, CarComponent, WheelsComponent, HomeComponent ], providers: [ CarService ], // <-------- SEE HERE bootstrap: [ AppComponent ] }) export class AppModule { }

© www.soinside.com 2019 - 2024. All rights reserved.