Angular RxJs 自动刷新组件

Tec*_*hie 1 observable rxjs angular

我正在开发 Angular 8 应用程序。要求每 5 秒自动刷新一次组件。我使用了下面的代码。

刷新.componenet.ts:

import { Observable, Subscription, interval } from 'rxjs';
.
.
listStudents$: Observable<StudentModel[]>;
private updateSubscription: Subscription;

constructor(
    private listStudentsService: ListStudentsService
  ) { }

ngOnInit(): void{
    this.GetStudentsBySubject();        
  }

private GetStudentsBySubject() {    
    this.updateSubscription = interval(5000).subscribe((val) => {
      this.listStudents$ = this.listStudentsService.getStudentsBySubject(this.subject);      
    });
  }

  ngOnDestroy() {
    this.updateSubscription.unsubscribe();
  }

Run Code Online (Sandbox Code Playgroud)

上面的代码运行完美,每 5 秒刷新一次组件。

该组件获取 中的学生列表ngOnInit()。然后每 5 秒刷新一次数据。但问题是,该组件第一次加载数据也会等待 5 秒。

如何有条件地将该组件中的自动刷新设置为每 5 秒刷新一次,而无需等待第一次。

Zac*_*ier 5

您可以使用计时器,这是 rxjs 的另一个功能。它的使用有一个初始延迟和一个周期。

https://www.learnrxjs.io/operators/creation/timer.html

this.updateSubscription = timer(0, 5000).subscribe((val) => { ...
Run Code Online (Sandbox Code Playgroud)