How to Cancel API Requests If You Are Using Observable Pipe in Angular

How to Use “takeUntil” to Cancel Older Requests

Photo by Anwaar Ali on Unsplash

In an e-mail sign up form, async validation was used to check if typed username was taken or not. “updateOn” value was set as ‘blur’ but changing it to ‘change’ would make it more user friendly.

updateOn” option’s possible values are ‘change’, ‘blur’ and ‘submit’. You can read more about “updateOn” option here.

By changing it to ‘change’, more API requests will be made because now we will be querying if the username is available every time the user types in or deletes a new character.

Since there will be much more requests and network problems where previous requests will take longer than newer ones, it would be nice to cancel the previous request before making a new one.

In the validation code, pipe was used to decide the value of show error flag variable. It would also be possible to convert to subscribe -> response, error, completion handler function style like:

Instead, I kept the current flow but added “takeUntil” method as suggested here by user184994.

You can also check the example under “Unsubscribing Declaratively with takeUntil” title here.

This is my implementation (search for cancelCheckUsername$ for its usage):

You can check if the field is valid by:


To show your error / info message:

<div *ngIf="!showErrorMessage; else error">

Happy Coding!

I would love to change the world, but they won’t give me the source code | coding 👩🏼‍💻 | coffee ☕️ | jazz 🎷 | anime 🐲 | books 📚 | drawing 🎨