我在项目中使用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);
});
}
以上就是我所掌握的。
我需要每分钟检查一次结果而又不会减慢我的应用程序的速度(因为我将有多个进程在执行此操作)。
我该怎么做?
答案 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
属性是为了避免进行取回操作。