Search code examples
angulartypescriptpolling

How can i call service every 1 second and check the response with angular2?


I have a service implemented as below,

export class UploadPollingService {
    constructor(private http: Http, private appConfig: AppConfigService) { }
    checkUploadInfo(term: string, ): Observable<Event[]> {
        return this.http
            .get(this.appConfig.getAPIUrl() + `/checkStatus?processId=${term}`)
            .map(this.extractData)
            .catch(this.handleErrors);
    }

I am using this inside a component, and i want to call this service every 1 second and check status, basically do a polling. how to do?

this.uploadPollingService.checkUploadInfo()

Solution

  • you have to use your service method within timeinterval like this

       ngOnInit(){
       this.interval = setInterval(() => {
            this.checkUpdate();
        }, 1000);
       }
    
        ngOnDestroy() {
        if (this.interval) {
            clearInterval(this.interval);
        }
       }
    
      checkUpdate(){
        this.uploadPollingService.checkUploadInfo()
          .subscribe(res => {
            console.log(res, "Response here");
          },
          err => {
            console.log(err);
          })
      }
      ....
    
    
    
      export class UploadPollingService {
        constructor(private http: Http, private appConfig: AppConfigService) { }
        checkUploadInfo(term?: string): Observable<Event[]> {
            return this.http
                .get(this.appConfig.getAPIUrl() + `/checkStatus?processId=${term}`)
                .map( res => {
                  return [{ status: res.status, json: res.json() }]
                })
                .catch(this.handleErrors);
        }