首页 > 解决方案 > 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?

标签: angulartypescriptrxjsangular6

解决方案


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) 发出值,直到取消订阅。


推荐阅读