Reputation: 41
how to monitor the duration of an http request with Observables Angular 4.x before timeoutWith (30s)?
Basically, I want to trigger an event in Application Insights after 5s.
My code:
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, '*');
});
Upvotes: 4
Views: 1098
Reputation: 191789
If I understand your question, you want to make an API call that times out with an error after 30 seconds. If the API call takes longer than 5 seconds, you want it to continue and use the data from the API but also track this as an event. If the API call completes in less than 5 seconds, don't track the event and use the data from the API as normal. I would actually do this using two separate observables: one for the 5 second timeout and the other for the service request itself.
A much simpler version can be illustrated like so:
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!'));
Using your code I think you would write it like so:
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, '*');
});
Upvotes: 2