1

I have code in app.component, which get all users

I am trying to refresh my page every second, because if i have 2 opened windows and make any CRUD actions, second window will show old data, without new developer / etc.

I am trying to use ngOnDestroy, but it does not work:

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);
      }
    );
  }
}

How looks my service method:

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

1 Answer 1

1

interval from rxjs is a Observable, and you need to subscribe for attach an event

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);
      }
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.