Search code examples
angularrxjspolling

Angular 2, Polling http request and wait for slow responses


I have a service that get data from a server every 3 seconds. Sometimes the server is very slow and many responses comes after 5 or 6 seconds. When this happen ,my service starts to cancel each request instead of waiting the pending one. How can I prevent this?

public getCallDiagnostic():Observable<IRespWidgets>{

        let body = JSON.stringify({manager:"CallDiagnosticServiceManager",
                                   action:"GetCallDiagnostic",
                                   WEB_USER_TOKEN:this._authenticationService.getUserToken()});     
        let options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});

        return  Observable.timer(0,3000)
                .switchMap(()=>this._http.post(this._apiUrl,body,options))                      
                .map(res => <IRespWidgets>res.json().data)          
                .catch(this.handleError);       
    }

Solution

  • Your requests are getting cancelled since you are using switchMap. If you want to receive the response from every request, just use mergeMap:

    return  Observable.timer(0,3000)
                .mergeMap(()=>this._http.post(this._apiUrl,body,options))                      
                .map(res => <IRespWidgets>res.json().data)          
                .catch(this.handleError);       
    

    This will never cancel a request and you'll get back the response from every request.

    Edit: If you want to perform the next request as soon as the previous arrives you can use concatMap. ConcatMap will take the next value and process it. It will not take a next value (even if it arrives) as long as the previous one isn't handled.

    return  Observable.timer(0,3000)
                .concatMap(()=>this._http.post(this._apiUrl,body,options))                      
                .map(res => <IRespWidgets>res.json().data)          
                .catch(this.handleError);