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

Angular 6 - run method in service every 10 seconds

我有这个服务使用 HttpClient 来获取一些数据:

checkData() {
    return this.http.get('my url');
}

我在页脚组件上调用它并显示结果:

ngOnInit() {
    this.myservice.checkdata().subscribe( result => { this.statustext = result } );
}

这可行,但我需要此方法每 10 秒 运行 一次,以便它是最新的。

我该怎么做?

在您的 checkData 方法中,您可以这样做:

import { timer, of } from 'rxjs';
import { switchMap, catchError } from 'rxjs/operators';

checkData() {
    return timer(0, 10000)
        .pipe(
           switchMap(_ => this.http.get('my url')),
           catchError(error => of(`Bad request: ${error}`))
        );
}

然后您的订阅将每 10 秒获取一次 http 调用的结果。

尝试使用来自 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();
    }
}
来自 RxJS 的

interval(10000) 是不合适的,因为它只会在 10 秒后开始发出值,而不是第一次立即发出值(我认为这不是你想要的)。

但是,timer(0, 10000) 将立即发出值 (0) 并每 10 秒发出一次值 (10000),直到取消订阅。

执行此操作的 rxjs 方法如下。

import { interval } from 'rxjs/observable/interval';
import { map } from 'rxjs/operators';

const timeInterval$ = interval(10000);

timeInterval$.pipe(
  map( () => this.http.get(//some url);
);

使用rxjs计时器在启动时调用api请求,然后每10秒调用一次。

这个最好用rxjs来分而治之

首先,导入以下内容:

import { timer, Observable, Subject } from 'rxjs';
import { switchMap, takeUntil, catchError } from 'rxjs/operators';

然后添加属性处理请求到api:

private fetchData$: Observable<string> = this.myservice.checkdata();

接下来,添加属性来处理时序:

private refreshInterval$: Observable<string> = timer(0, 1000)
.pipe(
  // This kills the request if the user closes the component 
  takeUntil(this.killTrigger),
  // switchMap cancels the last request, if no response have been received since last tick
  switchMap(() => this.fetchData$),
  // catchError handles http throws 
  catchError(error => of('Error'))
);

最后,如果组件被杀死,则触发 kill 命令:

ngOnDestroy(){
  this.killTrigger.next();
}

这里是StackBlitz Demo.

希望对您有所帮助

export class YourComponent implements OnInit, OnDestroy {
  private alive: boolean;

  constructor(){}

  ngOnInit(){
    this.alive = true;
    TimerObservable.create(0, 10000)
      .pipe(
        takeWhile(() => this.alive)
      )
      .subscribe(() => {
        this.myservice.checkdata().subscribe( result => { this.statustext = result } );
      });
  }

  ngOnDestroy(){
    this.alive = false;
  }
}

我指的是angular8:

请注意timer和interval的区别。

如果你想延迟单个函数调用,你会使用计时器,但如果你想按顺序触发多个函数调用,你想使用一个 invertal,延迟时间为:http://tutorials.jenkov.com/angularjs/timeout-interval.html

我在该博客中发现以下代码 post:http://tutorials.jenkov.com/angularjs/timeout-interval.html

ngOnInit() {
    interval(5000)
      .pipe(
        startWith(0),
        switchMap(() => this.apiService.getTweets())
      )
      .subscribe(res => this.statuses = res.statuses})
    ;
  }

你可以使用setInterval,很简单

setInterval(console.log('hi'), 10000);

每 10 秒运行一次