问题
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