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

时间:2017-05-22 12:05:58

标签: javascript angular

我已将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处理事件?

The plunker sample is not working(对不起,这是我的第一个插件示例),但会查看我的应用是如何安排的。

1 个答案:

答案 0 :(得分:9)

Hello_ friend。

所以基本上如果你想在你的应用程序中全局使用事件,你可以将ServiceEventEmitter结合使用

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

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

然后在子组件中使用此服务来发出类似 wheels.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 ...');
    }; 
}

然后从 AppComponent 捕获此事件,例如 app.component.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();
  }
}

I M P O R T A N T ______________

如果您希望自己的服务全球,则需要在顶级提供商中声明,例如 app.module.ts 是一个好地方:

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 { }

CLICK HERE TO SEE THE DEMO