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

查看:32
本文介绍了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 请求,然后每 10s 调用一次.

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天全站免登陆