angular - Angular 6 - run method in service every 10 seconds
问题描述
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 } );
}
This works, but I need this method to be run every 10 seconds so it's up to date.
How can I do this?
解决方案
timer
从 RxJS尝试:
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) 发出值,直到取消订阅。
推荐阅读
- python - Python, webkit2 gtk - 如何在 python 程序中使用 webkit 中的代理
- emacs - 缓冲组织到乳胶导出
- ios - 使用用户输入的数据到数组中更新 Swift 中的 UIPickerView 的问题
- c# - 结合包含和 EF 中的 where 不起作用
- sql - 更改 DB2 脚本中的分隔符
- html - 我在 html 中遇到 VS Code 自动完成类名的问题
- angular-reactive-forms - 在没有 ngmodel 的情况下,无法在 Reactive-form Angular 中实现两种方式绑定
- javascript - 将 react-select 默认值设置为 Formik 初始状态值
- mysql - 将数据库的sql脚本导入phpmyadmin后出现缺失索引错误的解决方法是什么
- apache-kafka - Spring cloud Stream kafka binder - 主题的自动配置