Angular 6 - 每 10 秒运行一次服务方法

标签 angular typescript rxjs angular6

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

相关文章:

reactjs - 如何在 _document 中添加自定义属性和扩展 DocumentInitialProps 类型?

javascript - 如何按顺序调用两个 API 并将两者的数据作为单个 Observable 返回

angular - 为什么当我单击使用 routerLink 和 queryParams 构建的链接时没有任何反应?

javascript - Angular 2子组件接收祖先事件

angular - 使用异步管道依次执行 Observable

javascript - 如何制作一个可追加的可观察队列?

angular - ngrx 从效果中多次分派(dispatch)相同的 Action

Angular 6 : Local workspace file ('angular.json' ) could not be found

javascript - 当我从使用服务获取的数组中删除一个元素时,它在哪里被删除?

css - 带粘性标题的 Angular Material 表