我有这个服务使用 HttpClient 来获取一些数据:
checkData() {
return this.http.get('my url');
}
我在页脚组件上调用它并显示结果:
ngOnInit() {
this.myservice.checkdata().subscribe( result => { this.statustext = result } );
}
这可行,但我需要此方法每 10 秒运行一次,以便它是最新的。
我该怎么做?
最佳答案
尝试使用来自 RxJS 的 timer
:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription, timer } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { MyService } from 'path/to/the/service/my-service.service';
@Component({
......
})
export class MyExampleComponent implements OnInit, OnDestroy {
subscription: Subscription;
statusText: string;
constructor(private myService: MyService) {}
ngOnInit() {
this.subscription = timer(0, 10000).pipe(
switchMap(() => this.myService.checkdata())
).subscribe(result => this.statusText = result);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
interval(10000)
来自 RxJS 是不合适的,因为它只会在 10 秒后开始发出值,而不是第一次立即发出值(我认为这不是你想要的) .
但是,timer(0, 10000)
将立即 (0) 和每 10 秒 (10000) 发出值,直到取消订阅。
关于Angular 6 - 每 10 秒运行一次服务方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50585764/