微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我有一个图表配置(带有amCharts),其中为子弹注册一个eventListener。此事件侦听器触发了我的图表服务中的另一个功能

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

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

task remove(type: Delete) {
    delete 'myFile.txt'
}

task remove(type: Exec) {
    commandLine 'del','myFile.txt','/q'
}

task remove {
    doFirst {
        exec {
            commandLine 'del",'/q'
        }
    }
}

应触发我组件中的方法(chart.component.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;
  }
}

解决方法

您可以在服务中定义一个主题,该主题将在每次触发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,() => 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();
  }

真正 很重要,在组件销毁时退订,否则会发生内存泄漏。

(我在这里直接写了这个,也许那里有一两个错字)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。