Making polling request in Angular 2 using Observable

无人久伴 提交于 2019-12-21 09:07:47

问题


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.


回答1:


Try

return Observable.interval(2000) 
        .switchMap(() => this.http.get(url))
        .map(res:Response => res.json());



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/35592716/making-polling-request-in-angular-2-using-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!