我如何每 1 秒调用一次服务并使用 angular2 检查响应?
How can i call service every 1 second and check the response with angular2?
我有如下实现的服务,
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()
而不是 this.uploadPollingService.checkUploadInfo() 使用下面的代码:
interval: any;
ngOnInit(){
this.interval = setInterval(() => {
this.uploadPollingService.checkUploadInfo() ;
}, 1000);
}
ngOnDestroy() {
if (this.interval) {
clearInterval(this.interval);
}
}
希望对您有所帮助!!!
您必须像这样在 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);
}
我有如下实现的服务,
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()
而不是 this.uploadPollingService.checkUploadInfo() 使用下面的代码:
interval: any;
ngOnInit(){
this.interval = setInterval(() => {
this.uploadPollingService.checkUploadInfo() ;
}, 1000);
}
ngOnDestroy() {
if (this.interval) {
clearInterval(this.interval);
}
}
希望对您有所帮助!!!
您必须像这样在 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);
}