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

Pau*_*l B 9 rxjs typescript angular angular6

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

checkData() {
    return this.http.get('my url');
}
Run Code Online (Sandbox Code Playgroud)

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

ngOnInit() {
    this.myservice.checkdata().subscribe( result => { this.statustext = result } );
}
Run Code Online (Sandbox Code Playgroud)

这有效,但我需要每10秒运行一次这样的方法,因此它是最新的.

我怎样才能做到这一点?

Adr*_*IER 16

timer从RxJS 尝试:

import { Subscription, timer } from 'rjxs';
import { switchMap } from 'rxjs/operators';

subscription: Subscription;
statusText: string;

ngOnInit() {
    this.subscription = timer(0, 10000).pipe(
      switchMap(() => this.myservice.checkdata())
    ).subscribe(result => this.statustext = result);
}

ngOnDestroy() {
    this.subscription.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)

interval(10000) 从RxJS发出数据是不合适的,因为它将仅在10秒后开始发出值,而不是在第一次时立即发出值(我认为这不是您要的内容)。

但是,timer(0, 10000)会立即(0)和每10秒(10000)发出值,直到取消订阅为止。

  • 不错的提示,干净又漂亮 (3认同)

Fai*_*sal 10

使用rxjstimer在启动时调用api请求,然后每隔10秒调用一次api请求.

最好通过使用rxjs来划分和征服.

首先,输入以下内容:

import { timer, Observable, Subject } from 'rxjs';
import { switchMap, takeUntil, catchError } from 'rxjs/operators';
Run Code Online (Sandbox Code Playgroud)

然后添加属性来处理对api的请求:

private fetchData$: Observable<string> = this.myservice.checkdata();
Run Code Online (Sandbox Code Playgroud)

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

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'))
);
Run Code Online (Sandbox Code Playgroud)

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

ngOnDestroy(){
  this.killTrigger.next();
}
Run Code Online (Sandbox Code Playgroud)

这是一个StackBlitz演示.