As far as I know there is numerous ways to interact between parent - child and child - parent components, like EventEmitter
for example. But is there any way to interact between components that are not parent - child or child -parent relations, different from using Service for this purpose?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Use this class
import { EventEmitter, Injectable } from "@angular/core";
@Injectable()
export class SharedService {
private emitter: EventEmitter<any>;
constructor() {
this.emitter = new EventEmitter<any>();
}
getEmitter(): EventEmitter<any> {
return this.emitter;
}
emit(data: any): void {
this.emitter.emit(data);
}
}
and subscribe to event in components like
@Component({
template: ''
})
export class MyComponent{
constructor(private emitter: SharedService){
this.emitter.getEmitter().subscribe(e => {
// do stuff here
});
}
}
dont forget to add it to NgModule and use it as like services.