I want to create a custom event which can trigger from any component and get listened to any component within my angular 7 app

泄露秘密 提交于 2019-12-26 02:43:05

问题


I want to create a custom event which can trigger from any component and get listened to any component within my angular 7 app

Suppose I have 1 component in which I have a button on click on which I want to trigger my custom event with some data. Next, there will be another component which will constantly listening for that event when it triggers it will execute some code and update the ui accordingly.

How should I implement it?


回答1:


Well, well, well, what you're looking for is a Shared Service. This shared service will have a BehaviorSubject that will act as a source for the data. Through this, you will be able to push new data streams. And then you will expose this BehaviorSubject asObservable.

You will then subscribe to this Observable from all the components where you want to listen for data changes and then react accordingly.

This is what this is going to look like in code:

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';

@Injectable()
export class SharedService {

  private data: BehaviorSubject<any> = new BehaviorSubject<any>(null);
  data$: Observable<any> = this.data.asObservable();

  constructor() { }

  setData(newData) {
    this.data.next(newData);
  }

}

You can now inject the SharedService in any controller you want and call setData from the component that you want to push new data from(see the AppComponent from the Sample StackBlitz for more details). And then you'll also be injecting the SharedService in other components and in there, you'll subscribe to data$ in their ngOnInit(see the HelloComponent from the Sample StackBlitz for details)

Here's a Sample StackBlitz for your ref.



来源:https://stackoverflow.com/questions/53354366/i-want-to-create-a-custom-event-which-can-trigger-from-any-component-and-get-lis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!