I run an internal Angular project that I want to introduce a "Cancel Request" button to. We have a search function that takes a bunch of parameters, but these requests can take up to two digit amount of seconds (10 and above). Usually that happens when someone types something too explicit into the search field, because we do a LIKE/contains search.
I want to be able to cancel these requests, so my code doesn't execute when returned to the component. That way, I can quickly cancel the request and send a new one.
Right now I set the button to disabled, so the user can't easily send a new request. If I don't do that, the following problem happens:
Obviously that's not optimal.
Code to play around with (click the Get stuff
button and a cancel button appears): https://stackblitz.com/edit/angular-cgmyvc
To be able to cancel requests you should firstly stop converting observable into Promise and use subscriptions instead.
Your service should be:
export class TestService {
constructor(private http: HttpClient) { }
public GetStuff() {
return this
.http
.get("https://jsonplaceholder.typicode.com/todos/1")
}
}
Now it returns an observable instead of promise.
Then in your component:
export class AppComponent {
constructor(private service: TestService){}
public request;
public Result;
public GettingStuff = false;
async ngOnInit() {
}
public GetStuff() {
this.GettingStuff = true;
this.request = this.service.GetStuff().subscribe((res) => {
this.Result = JSON.stringify(res);
this.GettingStuff = false;
})
}
public async CancelGettingStuff() {
console.log('cancelled');
this.request.unsubscribe();
this.GettingStuff = false;
}
}
As you see now I put the subscription into a variable request
. If it is necessary to cancel request - we just call an unsubscribe
method.
Here is the working stackblitz.
I recommend to emulate slow internet via developer tools before testing.
You will see that request is canceled each time you press cancel
button.