9

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.

3 Answers 3

12

Try

return Observable.interval(2000) 
        .switchMap(() => this.http.get(url))
        .map(res:Response => res.json());
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this. It still gives me the error. However, it does the polling in any case.
5

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()));

Comments

2

What you could do is, don't forget to cleanup you setInveral otherwise it will run forever :

let myObservable = new Observable(observer => {
     let count = 0;
     let interval = setInterval(() => {
           observer.next(count++);
  },2000);

 //disposal function
return() => {
   clearInterval(interval);
 }
});


let subscriber = myObservable.subscribe(
  val => console.log(val),
  err => console.log(err),
  _ => console.log('done')
);

subscriber.unsubscribe();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.