Hi guys,
in our custom widget we fetch measurement data via:
this.measurements.list(filter);
In some cases, this takes some time … the customer is switching the dashboard before the requests finishes.
The problem is that this request is still running in the background after switching dashboard and therefore slows down the performance.
Is there a known way to list such requests and abort them when switching dashboard / destroying the component?
Thanks in advance, regards
Hi,
Cumulocity has no built-in registry that lists running requests. Instead, you can attach an AbortSignal to the requests of each component and abort it when Angular destroys the component. The browser then cancels the HTTP request.
MeasurementService.list() has no signal parameter. The underlying FetchClient does pass signal on to fetch, though. You can give the widget its own FetchClient that adds the signal, and its own MeasurementService that uses that client:
import { DestroyRef, Provider, inject } from '@angular/core';
import { FetchClient, MeasurementService, Realtime } from '@c8y/client';
export function cancelOnDestroy(): Provider[] {
return [
{
provide: FetchClient,
useFactory: () => {
const root = inject(FetchClient, { skipSelf: true });
const controller = new AbortController();
inject(DestroyRef).onDestroy(() => controller.abort());
const client = Object.create(root) as FetchClient;
// Only cancel reads; writes always complete
client.fetch = (url, init = {}) =>
root.fetch(url, (init.method ?? 'GET') === 'GET' ? { ...init, signal: controller.signal } : init);
return client;
},
},
{
provide: MeasurementService,
useFactory: () => new MeasurementService(inject(FetchClient), inject(Realtime)),
},
];
}
Then add it to your widget:
@Component({
// ...
providers: [cancelOnDestroy()],
})
export class MyWidgetComponent {
private measurements = inject(MeasurementService);
async load(filter) {
try {
const { data } = await this.measurements.list(filter);
// ...
} catch (e) {
if (e?.name !== 'AbortError') throw e; // a cancelled request is expected
}
}
}
How it works:
- When it aborts: Angular destroys the component when the user switches dashboards. The DestroyRef callback then aborts all pending GET requests from this widget
- What it affects: only services provided in the component use the scoped client. The rest of the application keeps using the global FetchClient. To cover more services (for example InventoryService or EventService), add the same useFactory entry for each
- Errors: a cancelled request rejects with an AbortError. Ignore it in your error handling so the user doesn’t see an error message
- Not using @c8y/client: if you call fetch directly, pass the same signal: fetch(url, { signal: controller.signal }).
Best regards
Thanks a lot, we will try it out! Regards