Angular 2+每分钟运行一次服务

时间:2019-01-30 11:35:13

标签: angular typescript observable

我在项目中使用angular 7,我想知道如何每隔(例如)分钟检查一次结果却没有冻结我的应用程序。

因此,我有一项可从api请求数据的服务:

服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class DataService {

  baseUrl = 'some url here';


  constructor(private http: HttpClient) {}

  get_result() {
    return this.http.get(this.baseUrl + '/result');
  }

}

组件

 ngOnInit() {
    this.dataService.get_result().subscribe((res: any[]) => {
      console.log(res);
    });
  }

以上就是我所掌握的。

我需要每分钟检查一次结果而又不会减慢我的应用程序的速度(因为我将有多个进程在执行此操作)。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

将获取代码移至某个函数,然后使用诸如以下的间隔函数

 fetchResults(){
    this.isProcessing=true;
     this.dataService.get_result().subscribe((res: any[]) => {
      console.log(res);
      this.isProcessing=false;
    });
}

然后将ngoninit更改为

ngOnInit() {
   this.fetchResults()
    interval(60000).subscribe(val => {
    if (!this.isProcessing) {
    this.fetchResults();
    }
  })
  }

这里的isProcessing属性是为了避免进行取回操作。