Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making polling request in Angular 2 using Observable

I have the following code to make a polling GET request in AngularJS 2:

 makeHtpGetRequest(){
            let url ="http://bento/supervisor/info";
            return Observable.interval(2000)
                .map(res => res.json()) //Error here
                .switchMap(() => this.http.get(url));

            /*
    This portion works well
    return this.http.get(url)
                .map(res =>res.json());*/
        }

TypeScript is giving me an error make the response in JSON format (check comment in the code.

TypeError: res.json is not a function

Surprisingly, it was working for some time and I am not sure if I changed anything else, but it stopped working.

The commented part in the code works very well.

like image 249
kosta Avatar asked Feb 24 '16 03:02

kosta


2 Answers

It might be too late, but it might still help someone.

According to doc

This is not Angular's own design. The Angular HTTP client follows the ES2015 specification for the response object returned by the Fetch function. That spec defines a json() method that parses the response body into a JavaScript object.

I think json function only exists in http's response

I would try

return Observable.interval(2000) 
        .switchMap(() => this.http.get(url).map(res:Response => res.json()));
like image 90
maxisam Avatar answered Sep 20 '22 17:09

maxisam


Try

return Observable.interval(2000) 
        .switchMap(() => this.http.get(url))
        .map(res:Response => res.json());
like image 39
Mark Rajcok Avatar answered Sep 20 '22 17:09

Mark Rajcok