Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Angular 6 – run方法每10秒服务一次大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个服务使用httpClient来获取一些数据:

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

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

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

这有效,但我需要每10秒运行一次这样的方法,因此它是最新的.

我怎样才能做到这一点?

@L_696_5@

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

最好通过使用rxjs来划分和征服.

首先,输入以下内容

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

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

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

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

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命令:

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

这是一个StackBlitz Demo.

大佬总结

以上是大佬教程为你收集整理的Angular 6 – run方法每10秒服务一次全部内容,希望文章能够帮你解决Angular 6 – run方法每10秒服务一次所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。