Вы можете использовать BehaviorSubject
. Вот как.
Шаблон компонента приложения:
App Component!
<hello></hello>
<sibling></sibling>
1007 * Организация мероприятий *
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class EventService {
event: BehaviorSubject<any> = new BehaviorSubject<any>(null);
emitEvent(data) {
console.log('next Called with ', data);
this.event.next(data);
}
}
HelloComponent:
import {Component, Input} из '@ angular / core';
import { EventService } from './event.service';
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
constructor(private eventService: EventService) {}
ngOnInit() {
this.eventService.event
.subscribe(data => {
console.log('data received', data);
this.someMethod(data);
});
}
someMethod(data) {
console.log('some method got called!', data);
}
}
Siblingcomponent:
import { Component, Input } from '@angular/core';
import { EventService } from './event.service';
@Component({
selector: 'sibling',
template: `<button (click)="onClick()">Call Hello Component's Method</button>`,
styles: [`h1 { font-family: Lato; }`]
})
export class SiblingComponent {
constructor(private eventService: EventService) {}
onClick() {
console.log('onClick Called');
this.eventService.emitEvent({ foo: 'bar' });
}
}
Вот вам StackBlitz для справки.