Angular8:实时刷新数据



我在app.component中有代码,它可以获得所有用户的

我试图每秒刷新一次我的页面,因为如果我有两个打开的窗口并进行任何CRUD操作,第二个窗口将显示旧数据,而没有新的开发人员等。

我正在尝试使用ngOnDestroy,但它不起作用:

export class AppComponent implements OnInit{
interval = interval(1000); // 1s 
ngOnDestroy() {
if (this.interval) {
// @ts-ignore
clearInterval(this.interval);
this.getDevelopers();
}
}

public getDevelopers(): void {
this.developerService.getAllDevelopers().subscribe(
(response: GetByIdDeveloperResponse[]) => {
this.developers = response;
},
(error: HttpErrorResponse) => {
alert(error.message);
}
);
}
}

看起来我的服务方法如何:

public getAllDevelopers(): Observable<GetByIdDeveloperRequest[]> {
return this.http.get<GetByIdDeveloperResponse[]>(`${this.apiServerUrl}/api/v2/developers`);
}
rxjs的

间隔是可观测的,您需要订阅附加事件

import { interval } from 'rxjs';
export class AppComponent implements OnInit, OnDestroy {
$interval = interval(1000); // 1s
subInterval;
ngOnInit() {
this.subInterval = this.$interval.subscribe(() => this.getDevelopers());
}
ngOnDestroy() {
// destroy subscription
if( this.subInterval ){
this.subInterval.unsubscribe();
}
}

public getDevelopers(): void {
this.developerService.getAllDevelopers().subscribe(
(response: GetByIdDeveloperResponse[]) => {
this.developers = response;
},
(error: HttpErrorResponse) => {
alert(error.message);
}
);
}
}

最新更新