如何在timeoutWith(30s)之前使用Observables Angular 4.x监视http请求的持续时间?
基本上,我想在5s之后在Application Insights中触发一个事件。
我的代码:
this.activatedRoute.queryParams
.subscribe(params => {
this.service.obterContextos(params.IdentificadoresExternos)
.timeoutWith(environment.tempoLimiteCarregamento, Observable.defer(() =>
Observable.throw(this.alertarTimeOut())))
.subscribe(
data => {
});
this.appInsightsService.trackEvent('Telemetria - Cartão de Crédito',
telemetriaAI);
parent.postMessage(response, '*');
});
答案 0 :(得分:2)
如果我理解了您的问题,您希望在30秒后进行一次超时错误的API调用。如果API调用的时间超过5秒,您希望它继续使用API中的数据,但也会将其作为事件进行跟踪。如果API调用在不到5秒的时间内完成,请不要跟踪事件并正常使用API中的数据。我实际上是使用两个单独的observable来做到这一点:一个用于5秒超时,另一个用于服务请求本身。
更简单的版本可以这样说明:
import { of } from 'rxjs/observable/of';
import { defer } from 'rxjs/observable/defer';
import { _throw } from 'rxjs/observable/throw';
import { delay, timeoutWith, takeUntil } from 'rxjs/operators';
// The http request
const obs$ = of('Got the data');
const response$ = obs$.pipe(
delay(simulateDelay), // simulate the time it takes to complete the http request
// timeout error
timeoutWith(30000, defer(() => _throw('took too long -- error'))),
);
// handle data or error when request completes or times out
response$.subscribe(
data => console.log(data),
err => console.log(err),
);
// track event that the request is taking long after 5 seconds,
// but only if request has not completed yet
obs$.pipe(
delay(5000),
takeUntil(response$),
).subscribe(() => console.log('taking kinda long!'));
使用你的代码我想你会这样写:
const request$ = this.service.obterContextos(params.IdentificadoresExternos);
.timeoutWith(environment.tempoLimiteCarregamento, Observable.defer(() =>
Observable.throw(this.alertarTimeOut())))
request$.subscribe(data => { /* handle data */ });
timer(5000).pipe(takeUntil($request)).subscribe(() => {
this.appInsightsService.trackEvent('Telemetria - Cartão de Crédito',
telemetriaAI);
parent.postMessage(response, '*');
});