Angular async pipe: reminder
When you have an asynchronous operation, let’s say a service getting data from an HTTP request:
you normally have to manually subscribe to the Observable:
Well, let’s use some Angular magic:
async pipe, not only Angular is doing the subscription for you, but it will also do the unsubscription for you. Amazing!
Angular async pipe: the pitfall
Much better, right? But we lost control on something: the error callback. So you’d better be sure your Observable works in any case.
Unfortunately, in an web app, and especially in a Progressive Web App (PWA), all (non-cached) HTTP requests will fail when offline. Or the server could be temporary unavailable.
If you can provide a default value, RxJS
catchError operator is enough to handle this problem:
But very often, if there is no data for your page, there is no default value to provide and nothing to display.
Angular async pipe everywhere
If there is no Internet connection or the server is unavailable, it will redirect the user to an offline page of your choice (see the README on GitHub for advanced configuration).
As errors are handled, it’s now safe to use the
async pipe everywhere!
If you find problems with this lib, please open an issue on GitHub (commenting here is not the good place to do it).
By the same author
- Angular schematics extension for Visual Studio Code : graphic interface for Angular CLI commands
- @ngx-pwa/local-storage: Angular library for local storage
- typescript-strictly-typed: strict config for TypeScript and ESLint/TSLint
- Other popular Angular posts on Medium
- Follow me on Twitter
- Angular onsite trainings (based in Paris, so the website is in French, but my English bio is here and I’m open to travel)