Poll API using Angular HTTP Observable

时光毁灭记忆、已成空白 提交于 2019-12-06 06:30:10
siva636

This should be as simple as the following:

    pollInterval = 5000;
    const httpObservable = interval(pollInterval).pipe(
    switchMap(x => fetch(command, params?) )
   );

The pollInterval may be changed according to the requirements. interval and switchMap should be imported as follows:

import { interval } from 'rxjs';
import { switchMap } from 'rxjs/operators'; 

Using switchMap here helps to cancel any delayed pending http requests, this is good for performance particularly during intermittent Internet connections. That is why the RxJS reactive way of doing this is preferred over traditional methods such as setInterval().

Also a subscription should be made finally, otherwise nothing will happen:

httpObservable.subscribe(x => {});

You can also do like this if you dont want to use rxjs

 setInterval(function(){
      serviceObj.httpObservable.subscribe(x => {});
    }, 10000)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!