Forum Discussion
DEV29
Nov 01, 2024Copper Contributor
.NET Web API CancellationToken don't work with Angular .unsuscribe()?
In Angular, I make API calls by subscribing to observables. When a user cancels a request, the application unsubscribes to the subscription which cancels the request (I can see this in the network ta...
manojkke0529
Nov 02, 2024Copper Contributor
When using Angular's unsubscribe() to cancel HTTP requests, it does prevent the client from processing the response, but it does not necessarily signal the server to stop processing the request. The cancellation logic on the client side only affects the subscription in your Angular app; it does not communicate with the server to cancel the ongoing operation.
Why CancellationToken Might Not Work with Angular's unsubscribe():
- HTTP Protocol Limitation: Standard HTTP requests do not have a built-in mechanism for clients to notify the server to cancel the processing of a request once it has been sent.
- Client-Side Behavior: In Angular, unsubscribe() cancels the subscription to the observable, but it does not send an additional signal to the server to stop processing.
Solutions to Implement Server-Side Cancellation:
Client-Side Cancellation Support: Ensure your Angular client is configured to support request cancellation using AbortController:
- This can be done by integrating AbortController in Angular's HTTP client service to pass a cancellation signal with the request.
const controller = new AbortController();
const signal = controller.signal;
this.http.get('/api/your-endpoint', { signal }).subscribe(
data => { /* handle response */ },
error => { /* handle error */ }
);
// Call this to cancel the request
controller.abort();
- DEV29Nov 02, 2024Copper Contributor
Thanks for your reply, really appreciate it!
However, this doesn't seem to fire the endpoint in the.NET API - this is the code I have in Angular:
const controller = new AbortController(); const signal = controller.signal; this.http.get('/api/your-endpoint', { withCredentials: true, signal: signal }).subscribe( data => { /* handle response */ }, error => { /* handle error */ } ); // Call this to cancel the request controller.abort();Am I sending the signal correclty?