admin管理员组

文章数量:1356864

I have wheelsponent nested to carponent.

wheelsponent:

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!');

    };
}

Component carponent is not written at html page, but called through routing at car-routing.module.ts:

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

What I want is to handle event emitted from wheelsponent, not at carponent, but at appponent.

Is it possible to handle event at appponent?

The plunker sample is not working (sorry, this is my first plunkr example), but gives a view how my app is arranged.

I have wheels.ponent nested to car.ponent.

wheels.ponent:

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!');

    };
}

Component car.ponent is not written at html page, but called through routing at car-routing.module.ts:

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

What I want is to handle event emitted from wheels.ponent, not at car.ponent, but at app.ponent.

Is it possible to handle event at app.ponent?

The plunker sample is not working (sorry, this is my first plunkr example), but gives a view how my app is arranged.

Share Improve this question edited May 23, 2017 at 10:36 codtex 6,5582 gold badges20 silver badges36 bronze badges asked May 22, 2017 at 12:05 StepUpStepUp 38.3k16 gold badges92 silver badges157 bronze badges 4
  • Can you create a sample plunker with your project structure, because it's not really clear – codtex Commented May 22, 2017 at 12:11
  • Yes, it is possible to handle event-emitted @ (the root) app.ponent . I have done it without routes; but it should be possible with it too. if u can share the plunkr that would give perspective. – Plankton Commented May 22, 2017 at 12:24
  • @Plankton I've added plunker, but it is not working cause it is my first time at plunkr. – StepUp Commented May 22, 2017 at 13:05
  • @StepUp thanks I will have a look – codtex Commented May 22, 2017 at 13:15
Add a ment  | 

1 Answer 1

Reset to default 15

Hello_ friend.

So basically if you want to use events globally in your application you can use a Service in bination with EventEmitter

In this case you create a service for example car.service.ts

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

Then use this service in a child ponent to emit events like this wheels.ponent.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 ...');
    }; 
}

and then capture this event from AppComponent for example app.ponent.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.ponent.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 ponent is destroyed */
    this.subscription.unsubscribe();
  }
}

I M P O R T A N T______________

If you want your service to work globally you need to declare it in the top level providers for example app.module.ts is a good place:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent }  from './app.ponent';
import { CarComponent} from './cars/car.ponent';
import { WheelsComponent} from './cars/wheels.ponent';
import { HomeComponent} from './home.ponent';
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

本文标签: