Angular async pipe everywhere with ngx-pwa/offline

Cyrille Tuzi
Apr 12, 2018 · 2 min read
Image for post
Image for post

You know the Angular async pipe, right? Ever wanted to use it everywhere in your app? Then you’ll want @ngx-pwa/offline.

A French version of this post is available here.

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:

With the 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

Say hello to @ngx-pwa/offline. Follow Getting started on GitHub to install and initialize everything, then you’ll be able to use the catchOffline operator:

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!

Support

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store