在全球范围内发布事件

Geo*_*off 5 javascript typescript angular

我想要实现的是我想在angular2中全局发出一个自定义事件并让多个组件监听它,而不仅仅是父子模式

在我的事件源组件中,我有

export class EventSourceComponent{

  @Output() testev = new EventEmitter();

  onbtnclick(){
    this.testev.emit("i have emitted an event")
  }
 }
Run Code Online (Sandbox Code Playgroud)

现在我想要其他组件来获取此事件

export class CmpTwoComponent{

    //here get the emitted event with data
  } 
Run Code Online (Sandbox Code Playgroud)

我如何实现上述目标?

Mil*_*lad 4

您可以为此使用共享服务。

export class EventSourceComponent{
    constructor(private sharedService : SharedService){}


      onbtnclick(){
        this.sharedService.testev.next("i have emitted an event")
      }
 }

export class CmpTwoComponent{

//here get the emitted event with data

   constructor(sharedService : SharedService){

      sharedService.testev.subscribe((event)=>{console.log(event)})
   }

} 
Run Code Online (Sandbox Code Playgroud)

然后共享服务将是

@Injectable()
export class SharedService{

   public testev = new Subject()

}
Run Code Online (Sandbox Code Playgroud)

显然,如果您仍然需要Output父组件能够正常订阅,您也可以添加:

export class EventSourceComponent{

    @Output() testev = new EventEmitter();
    constructor(private sharedService : SharedService){}


      onbtnclick(){
        this.testev.emit("i have emitted an event")
        this.sharedService.testev.next("i have emitted an event")
      }
 }
Run Code Online (Sandbox Code Playgroud)