-1

我有一个图表配置(使用 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() {
    // ...
}
4

2 回答 2

1

您可以在服务中定义一个主题,该主题将在每次触发 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
}
...
于 2020-10-26T12:34:42.310 回答
1

您需要使用可观察对象:

服务:

 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();
  }

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

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

于 2020-10-26T12:35:38.830 回答