Author: Damian Gemza
Adding the @angular/pwa mechanism to your existing application
Without adding the PWA mechanism, your application will not work offline. To find out about it, open the
address in a Google Chrome browser, open the
developer tools using the F12 key, then open the Network tab, and select the Offline checkbox and refresh
the page. You will find out that the application cannot work without an Internet connection.
Do you think about what it's all about? After all, it was supposed to work offline and not - calmly! You will immediately learn how to make your application work offline.
In Angular 6 we gained a very convenient option, thanks to which we can use one command to configure the PWA mechanism in our application. Thanks to that, we can save ourselves the effort of modifying individual project files. In order to add PWA to your application, type the following command in the terminal:
ng add @angular/pwa
After performing the above command, some new files have been created in our project and some existing ones have been modified.
ngsw-config.json— this contains the Service Workers configuration, thanks to which it is possible to cache application data in PWA;
manifest.json— in this file you will find the configuration of the application's appearance. Here you can also change the name of the application, change the background and theme color;
assetsdirectory has been expanded with icons for different resolutions so that each type of device gets a customized icon for it.
app.module.ts— the ServiceWorkerModule module has been added to the main module of our application. This allows us to use various functions provided by Service Workers;
angular.json— several options for the configuration and operation of PWA have been added to this file;
package.json— a new @angular/pwa package has been added, which we added in the previous step;
index.html— a link to the manifest.json file was added as well as the theme color — the same color as defined in the manifest.json file.
In the picture below, the files that have been created are marked in red and those that have been modified with the
ng add @angular/pwa command in green.
What Service Workers are?
In the future, it will also include geofencing and periodical synchronization. Service Workers are very interesting because they also support offline mechanisms, thanks to which the programmer has complete control over the functionality of the application.
Service Workers switch off when not used to free up resources, and start-up automatically when needed. If you need to use some data that will always be the same, use the IndexedDB API.
In case something doesn't work for you, please check the code for this lesson on our repository
Previous lesson Download Next lesson
Spread the word:
Note: We can help you build your project.