我有如下实现的服务,
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()
答案 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);
}
}
希望它的帮助!!!