Angular 2. How interact between different level co

2020-05-03 10:59发布

问题:

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.



标签: angular