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

我只是一个虾纸丫 提交于 2019-12-01 12:00:28

问题


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

回答1:


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



回答2:


Instead of this.uploadPollingService.checkUploadInfo() use below code:

   interval: any;
   ngOnInit(){
   this.interval = setInterval(() => {
        this.uploadPollingService.checkUploadInfo() ;
    }, 1000);
   }

    ngOnDestroy() {
    if (this.interval) {
        clearInterval(this.interval);
    }
   }

Hope it's help!!!



来源:https://stackoverflow.com/questions/42919831/how-can-i-call-service-every-1-second-and-check-the-response-with-angular2

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