首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular8 :实时刷新数据

Angular8 :实时刷新数据
EN

Stack Overflow用户
提问于 2021-04-05 06:43:54
回答 1查看 145关注 0票数 1

我在app.component中有代码,它让所有的用户

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

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

代码语言:javascript
复制
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);
      }
    );
  }
}

我的服务方法怎么样:

代码语言:javascript
复制
  public getAllDevelopers(): Observable<GetByIdDeveloperRequest[]> {
    return this.http.get<GetByIdDeveloperResponse[]>(`${this.apiServerUrl}/api/v2/developers`);
  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-05 07:04:43

来自rxjs的间隔是可观察的,您需要订阅附加事件。

代码语言:javascript
复制
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);
      }
    );
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66949192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档