Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
992 views
in Technique[技术] by (71.8m points)

typescript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try with timer from 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) from RxJS is not appropriate, because it will start to emit values ONLY after 10sec and not immediatly for the first time (and I think that's not what you're looking for).

However, timer(0, 10000), will emit values immediatly (0) and every 10sec (10000) until unsubscription.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.7k users

...