Angular 6-运行方法每10秒运行一次 [英] Angular 6 - run method in service every 10 seconds

查看:83
本文介绍了Angular 6-运行方法每10秒运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用HttpClient获得此服务:

I have this service using HttpClient to get some data :

checkData() {
    return this.http.get('my url');
}

我在页脚组件上调用它并显示结果:

The on the footer component I call it and display the result :

ngOnInit() {
    this.myservice.checkdata().subscribe( result => { this.statustext = result } );
}

这可行,但是我需要每10秒运行一次此方法,以便它是最新的.

This works, but I need this method to be run every 10 seconds so it's up to date.

我该怎么做?

推荐答案

在启动时使用rxjs计时器调用api请求,然后每10秒调用一次.

Use rxjs timer to call the api request at startup and then every 10s.

最好通过使用rxjs进行分而治之.

This is best achieved by using rxjs to divide and conquer.

首先,导入以下内容:

import { timer, Observable, Subject } from 'rxjs';
import { switchMap, takeUntil, catchError } from 'rxjs/operators';

然后添加该属性以处理对api的请求:

Then add the property to handle request to the api:

private fetchData$: Observable<string> = this.myservice.checkdata();

接下来,添加属性以处理时间:

Next, add the property to handle the timing:

private refreshInterval$: Observable<string> = timer(0, 1000)
.pipe(
  // This kills the request if the user closes the component 
  takeUntil(this.killTrigger),
  // switchMap cancels the last request, if no response have been received since last tick
  switchMap(() => this.fetchData$),
  // catchError handles http throws 
  catchError(error => of('Error'))
);

最后,如果组件被杀死,则执行kill命令:

At last, fire the kill command if the component is killed:

ngOnDestroy(){
  this.killTrigger.next();
}

这是一个 StackBlitz演示 .

这篇关于Angular 6-运行方法每10秒运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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