我有这个服务使用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';
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.