2

I want to implement polling in my nativescript with angular application. I want to check for instance each second the state of my backend server. I have this service :

@Injectable()
export class StateService {
getStatus(): Observable<StateApp> {
        let headers = this.getHeaders();
        return this.http
            .get(BackendService.stateUrl, {
                headers: headers
            })
            .map(res => {
                return res.json() as StateApp
            })
            .catch(this.handleErrors);
}

And then I would like to susbscribe to this service and send a request to the server. In my component in my component I have the following code:

IntervalObservable.create(1000).subscribe(() => {
            this.statusService.getStatus()
                .subscribe(
                (next) => {
                    this.state = next;
                };
        });

I tried to implement the solution that I read here and that deals with the same issue ( but it's a post from almost 2 years ago) Angular2 http at an interval but for instance when I write IntervalObservable.takeWhile it doesn't exist anymore (rxjs version 5.4.3). So I was wondering what is the way of achieving the same result (i.e first time to not wait one second to obtain the result and to stop sending requests when component is destroyed)

Axel
  • 186
  • 3
  • 11

1 Answers1

10

You can use rxjs interval operator and implement polling. The following implemention will execute the this.statusService.getStatus() line in every 1000 ms interval :

 this.subscription = Observable.interval(1000).startWith(1)
 .mergeMap(() => this.statusService.getStatus())
 .subscribe((next) => {
     this.state = next;
 })

Update: with startWith(1) added, now, it will be immediately executed without any delay and after that it will be executed every 1 sec interval. I think this is what you want.

Or Another approach: you can use timer operator and do the following:

this.subscription = Observable.timer(0, 1000)
  .mergeMapTo(this.statusService.getStatus())
  .subscribe((next) => {
        this.state = next;
    }, (errRes)=>{
       console.log(errRes);
   });

In this approach, the timer operator will instantly execute and after that it will execute in every 1000 ms.

And unsubscribe the Observable components ngOnDestroy lifecycle hook.

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

Also don't forget to import :

  import {Observable} from 'rxjs/Observable';
  import 'rxjs/add/operator/mergeMap';
  import 'rxjs/add/operator/startWith';
  import 'rxjs/add/operator/mergeMapTo';
  import 'rxjs/add/observable/timer';
asmmahmud
  • 4,844
  • 2
  • 40
  • 47