/ angular2

Angular2 async http request

Imagine your are developing a real time data processing app where you have to do chained http request in 5 seconds of interval.

How you can do that ?
Simple, use rxjs Observable to handle 5sec delayed event and on the event do http request.

import {Observable} from "rxjs";

// You can write it where ever you want, here I'm putting it in OnInit
ngOnInit(){
    const timer = Observable.timer(5000, 5000);
    const subscription = timer.subscribe(
        (time: any) =>  {
            // It will be called on every 5sec
            makeRequest().subscribe(
                data => {
                    // Response
                },
                err => {
                    // Error
                }
            );
        }
    );
}

makeRequest(){
    return _http.post(_url, _params)
           .map(function (res) {
              return res.text();
           });
}

If you want to stop / unsubscribe,

subscription.unsubscribe();