Angular 6 – run方法每10秒服务一次
发布时间:2020-12-17 17:24:14 所属栏目:安全 来源:网络整理
导读:我有这个服务使用HttpClient来获取一些数据: checkData() { return this.http.get('my url');} 我在脚注组件上调用它并显示结果: ngOnInit() { this.myservice.checkdata().subscribe( result = { this.statustext = result } );} 这有效,但我需要每10秒运
我有这个服务使用HttpClient来获取一些数据:
checkData() { return this.http.get('my url'); } 我在脚注组件上调用它并显示结果: ngOnInit() { this.myservice.checkdata().subscribe( result => { this.statustext = result } ); } 这有效,但我需要每10秒运行一次这样的方法,因此它是最新的. 我怎样才能做到这一点? 解决方法
使用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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |