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

Ste*_*pUp 2 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!');

    };
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

plunker示例不起作用(对不起,这是我的第一个plunkr示例),但是给出了我的应用程序如何排列的视图.

cod*_*tex 10

你好朋友.

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

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

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

然后在子组件中使用此服务来发出类似wheel.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 ...');
    }; 
}
Run Code Online (Sandbox Code Playgroud)

然后从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();
  }
}
Run Code Online (Sandbox Code Playgroud)

IMPORTAN 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 { }
Run Code Online (Sandbox Code Playgroud)

点击这里查看演示

  • 不要从'rxjs'导入*!您要求typescript以这种方式加载整个rxjs库.而是从'rxjs'导入{Subscription} (2认同)