如何在执行服务中的方法时触发组件中的方法?

How to trigger a method in a component when a method in a service is executed?

我有一个图表配置(使用 amCharts),其中为项目符号注册了一个 eventListener。此事件侦听器触发我的图表服务中的另一个功能。

我想在图表服务中的 eventListener 被触发时立即在我的组件中触发一个方法。我怎样才能用 Angular 最好地解决这个问题?

我的服务 (chart.service.ts) 如下所示:

getSingleChart(chart, amChart) {
  // some configs
  // ...

  this.chart.updateChart(amChart, () => {
    // some configs
    // ...
    amChart.addListener('clickGraphItem', this.bulletClicked);
  });

  // I don't know if this method is needed?
  // The idea here was to execute the method in the component, if the bulletClicked pro is true
  chartBulletClicked() {
    return this.bulletClicked = true;
  }
}

我的组件中应该触发的方法(chart.component.ts):

onBulletClicked() {
    // ...
}

您可以在您的服务中定义一个主题,该主题将在每次您的 eventListener 被触发时发出,并在您的组件中订阅该主题并在每次新发射时调用您的方法:

您的服务:


private _chartEventTriggered$: Subject<void> = new Subject();

get chartEventTriggered$(): Observable<void> {
    return this._chartEventTriggered$.asObservable();
}

getSingleChart(chart, amChart) {
  // some configs
  // ...

  this.chart.updateChart(amChart, () => {
    // some configs
    // ...
    amChart.addListener('clickGraphItem', () => this._chartEventTriggered$.next());
  });

}

在您的组件中:

...
ngOnInit() {
    this.service.chartEventTriggered$.subscribe(() => this.onBulletClicked());
}

onBulletClicked() {
    // do stuff
}
...

您需要使用可观察对象:

服务:

 privatereadonly chartBulletClicked$$ = new Subject<void>();
 public readonly chartBulletClicked$ = this.chartBulletClicked$$.asObservable();


getSingleChart(chart, amChart) {
  // some configs
  // ...

  this.chart.updateChart(amChart, () => {
    // some configs
    // ...
    amChart.addListener('clickGraphItem', () => this.chartBulletClicked$$.next());
  });

  // I don't know if this method is needed?
  // The idea here was to execute the method in the component, if the bulletClicked pro is true
  chartBulletClicked() {
    return this.bulletClicked = true;
  }
}

组件:

  private subscriptions = new Subscription();
  ngOnInit(){
    this.subscriptions.add(
      this.myService.chartBulletClicked$.subscribe(() => {
        // Do what you need
      });
    );
  }

  ngOnDestroy() {
    this.subscriptions.unsubscribe();
  }

真的重要的是当你的组件被销毁时取消订阅,否则你会发生内存泄漏。

(我直接写到这里可能有一两个错别字)