Search code examples
angulartypescriptsubscription

call and wait in interval using subscribe in Angular 6


I call a method every 10000 time. I want to make this function getAllNotificationsActed0() invoked every 10 seconds and if the data did not come within this interval, do not call the function again. If the data is received within 10 seconds the function is called, if the data has not come within 10 sec of the function, do not call but wait.

service.ts

public NotifGetAllActedNoActive(): Observable<Notifications[]> {
  let headers = new Headers();
  headers.append('x-access-token', this.auth.getCurrentUser().token);
  return this.http.get(Api.getUrl(Api.URLS.NotifGetAllActedNoActive), {
    headers: headers
  })
    .map((response: Response) => {
      let res = response.json();
      if (res.StatusCode === 1) {
        this.auth.logout();
      } else {
        return res.StatusDescription.map(notiff => {
          return new Notifications(notiff);
        });
      }
    });
}

component.ts

ngOnInit() {
  this.subscription = Observable.interval(10000).subscribe(x => {
    this.getAllNotificationsActed0();
  });
}

getAllNotificationsActed0() {
  this.notif.NotifGetAllActedNoActive().subscribe(notification0 => {
    this.notification0 = notification0;
    if (this.isSortedByDate) {
      this.sortbydate();
    }
  });
}

Any idea please?


Solution

  • Try this in your component:

    import { takeUntil } from 'rxjs/operators';
    import { Subject, timer } from 'rxjs';
    
    private _destroy$ = new Subject();
    ngOnInit() {
        this.getAllNotificationsActed0();
    }
    ngOnDestroy() {
        this._destroy$.next();
    }
    getAllNotificationsActed0() {
        this.notif.NotifGetAllActedNoActive()
         .pipe(takeUntil(this._destroy$))
         .subscribe(notification0 => {
            this.notification0 = notification0;
            if (this.isSortedByDate) {
                this.sortbydate();
            }
            timer(10000).pipe(takeUntil(this._destroy$))
                .subscribe(t => this.getAllNotificationsActed0() );
        });
    }
    

    It's a good approach to stop pipe on component destroy. You can use Subject object to achive this. Also you can stop any pipes you have to stop on component destruction.