, , , , "" ( / ). , .
EmitService.
import { Injectable, EventEmitter } from '@angular/core';
@Injectable()
export class EmitService {
private _emitter;
constructor() {
this._emitter = new EventEmitter ( );
}
subscribeToServiceEmitter ( callback ) {
return this._emitter.subscribe ( b => callback ( b ) );
}
emitThisData ( data ) {
this._emitter.emit ( data );
}
}
, . CompOneComponent, , CompTwoComponent:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { EmitService } from '../emit.service';
@Component({
selector: 'app-comp-one',
templateUrl: './comp-one.component.html',
styleUrls: ['./comp-one.component.css']
})
export class CompOneComponent implements OnInit, OnDestroy {
private _sub;
constructor( private _emitSvc : EmitService ) {}
ngOnInit() {
this._sub = this._emitSvc.subscribeToServiceEmitter ( this.onEmittedEvent );
setTimeout( () => {
this._emitSvc.emitThisData ( 'DATA FROM COMPONENT_1' );
}, 2000 );
}
onEmittedEvent ( data ) {
console.log ( `Component One Received ${data}` );
};
ngOnDestroy ( ) {
this._sub.unsubscribe ( );
}
}
; , , :
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { CompOneComponent } from './comp-one/comp-one.component';
import { CompTwoComponent } from './comp-two/comp-two.component';
import { EmitService } from './emit.service';
@NgModule({
declarations: [
AppComponent,
CompOneComponent,
CompTwoComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
exports: [ ],
providers: [ EmitService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
. ( EventEmitter), , , , - . CLI, , , console.log, ( , , , , ). , EmitService, , .