一旦我将组件留在Angular中,就停止调用连续函数 [英] Stop a continuous function being called once I leave the component in Angular

查看:76
本文介绍了一旦我将组件留在Angular中,就停止调用连续函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular构建应用程序.作为其一部分,我每1分钟进行一次API调用以获取连续数据.我的代码看起来像这样.

I am building an app using Angular. As part of it, I am making an API call every 1 min for continuous data. My code looks like.

ngOnInit() {
    this.getRealTimeData();
  }

  intervalId : any

  getRealTimeData() {
    this.getChillerApiData()
    clearInterval(this.intervalId);
    this.intervalId = setInterval(() => {
      this.getChillerApiData();
    }, 1000);
  }

  getChillerApiData() {
    this.api.getFirstChillerData()
      .subscribe((first_data:any) => {
        this.first_api_data = first_data;
        console.log(this.first_api_data)
        this.putPrimaryPumpData();
      });
  }

我每1分钟或我提到的任何时间间隔获取一次数据.但是发生的事情是当我离开该组件并继续使用另一个组件时,仍然可以看到以指定的时间间隔定期进行API调用(我可以看到控制台日志).我该如何阻止这种情况的发生?我的意思是,一旦离开该组件,API调用也应该停止.

I am getting data every 1 min or whatever time interval I mention. But what is happening is when I leave the component and go on to another component, still I see API calls made regularly at specified interval (I can see the console logs). How do I stop that from happening? I mean once I leave this component API calls should also stop.

推荐答案

首先,这里有很多错误.

First of all there are so many things wrong here.

您称为订阅,并且不是取消订阅.您想取消订阅,并想清除间隔.如果未清除订阅,它将继续获取信息并继续重复.因此,每次触发订阅时都会调用putPrimaryPumpData.可以在多次同时运行中得出结论.

You call an subscribition and it's not unsubscribed. You want to unsubscribe the subscribition and you want to clear the interval. If the subscribition is not cleared it will keep getting info and keep repeating it. So putPrimaryPumpData will be called everytime the subscription is fired. Which can conclude in multiple running at the same time.

执行以下操作:

let sub = this.api.getFirstChillerData()
  .subscribe((first_data:any) => {
    sub.unsubscribe();
    this.first_api_data = first_data;
    console.log(this.first_api_data)
    this.putPrimaryPumpData();
  });

现在,这将不会像1000个循环中的100个那样创建. 其次,您可以像这样使用ngOnDestroy:

Now this will not create like 100 of 1000 of loops. Second you can use ngOnDestroy like:

ngOnDestroy() {
  clearInterval(this.intervalId);
}

这篇关于一旦我将组件留在Angular中,就停止调用连续函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆