Description
Which @angular/* package(s) are relevant/related to the feature request?
common
Description
I have a http resource which calls an endpoint with a pagination. The page size is calculated based on the component's host element width:
export class MyComponent implements OnDestroy {
readonly url = input.required<string>();
private readonly myResource = httpResource(() => ({
url: this.url(),
params: {
...(this.top() > 0 && { top: this.top() })
},
}));
private readonly elementRef = inject(ElementRef);
private readonly width = signal(0); // At this point, the calculated width of the element is 0
private readonly resizeObserver = new ResizeObserver(([entry]) =>
this.width.set(entry.contentRect.width),
);
private readonly top = computed(() => Math.floor(this.width() / 200));
constructor() {
this.resizeObserver.observe(this.elementRef.nativeElement);
}
ngOnDestroy() {
this.resizeObserver.disconnect();
}
}
It works fine, but there is an initial request where the top
is skipped. The reason is that at the time of creating the resource, the width of the host element is still 0 as it hasn't been rendered yet. One tick later, the resize observer pushes the width of the element, which triggers a new request and cancels the initial one.
I want to achieve that the initial request is skipped.
This has been already been requested in the RFC, but I don't understand how the proposed solution with Idle
should be implemented.
Proposed solution
The resource could expose an API that reactively allows to delay or skip requests of the resource, maybe something like the following:
const someBooleanFlag = signal(false);
httpResource('some-url', { requestWhile: () => someBooleanFlag() });
setTimeout(() => someBooleanFlag.set(true), 100);
Where in this example the request would be delayed by 100ms.
Alternatives considered
The calling of the httpResource()
function can be delayed by moving it to afterNextRender()
or another function, but this would complicate the usage as the injector
needs to be passed. Also developers may need to add code to handle the possibility of the resource being null or undefined.
Another alternative is writing an Interceptor which skips specific requests based on HttpContext
. This would also allow to skip requests after initialization.