我怎样才能每1秒拨打一次服务并用angular2检查响应?

时间:2017-03-21 06:25:10

标签: angular typescript polling

我有如下实现的服务,

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

我在组件内使用它,我想每1秒调用一次该服务并检查状态,基本上进行轮询。怎么办?

this.uploadPollingService.checkUploadInfo()

2 个答案:

答案 0 :(得分:5)

您必须在timeinterval这样的

中使用您的服务方法
   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);
    }

答案 1 :(得分:1)

而不是 this.uploadPollingService.checkUploadInfo()使用下面的代码:

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

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

希望它的帮助!!!