In this tutorial, we will see how to Enable Angular PWA to make the application work offline using the cache data. The Angular PWA service worker will make it happen and will cache the data for us. Using a PWA service worker Native mobile app can be created.
Angular PWA (Progressive Web App)
Using progressive web app feature in angular make your site available offline. PWA doesn’t need a different way to build an app, it just enhances your application by caching all the images, assets, even your API responses, and make your application work offline.
It can also install as an app on users’ home screen of phone whether it’s IOS or Android without downloading or installing manually through an app store.
Add Angular PWA
If you are starting a new application or if you want to add in an existing application.
Just the way we install NPM packages we will add the angular @angular/pwa
package using Angular’s CLI command.
ng add @angular/pwa
After adding PWA you can see it has added some new files i.e.
- A
manifest.webmanifest
file, - Different sizes of icons in the
src/assets/icons
folder, - The
ngsw-config.json
service worker configuration.
Manifest JSON
The manifest.webmanifest
file contains the application name, theme, and background color and list of different sizes of icons.
This configuration is applied when you add the app to the mobile it creates a web view with adding the name and icons to the app list and when the app is run the background and theme color is applied.
{
"name":"angular-pwa",
"short_name":"angular-pwa",
"theme_color":"#1976d2",
"background_color":"#fafafa",
"display":"standalone",
"scope":"/",
"start_url":"/",
"icons":[
{
"src":"assets/icons/icon-72x72.png",
"sizes":"72x72",
"type":"image/png"
},
{
"src":"assets/icons/icon-96x96.png",
"sizes":"96x96",
"type":"image/png"
},
...
]
}
manifest.webmanifest
file and the icons of different size from this link: App Manifest Generatorngsw-config
This ngsw-config.json
is a file or you can say its an ❤️ of an angular PWA. From this, you can able to manage a variety of different things associated with PWA.
Also, this is where we cache the API endpoint.
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/manifest.webmanifest",
"/*.css",
"/*.js"
]
}
}, {
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**",
"/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
]
}
}
]
}
Before we do something else let’s build and see what we can see in the developers console.
# Build the app with PRODUCTION
ng build --prod
# Go to DIST folder
cd dist/angular-pwa
# Serve with http-server
http-server -o
We cannot find the service worker as we are not running on HTTPS protocol, but you can see the manifest data is load.
Cache API Endpoints And External Resources
To make our content available we can cache the response of the API endpoints just by mentioning the External Resources URL and API Endpoints into the ngsw-config.json
file.
Cache External Resource
Consider we loading google fonts into our application and we want to make it load without network.
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [...
],
"urls": [
"https://fonts.googleapis.com/**" // Cache external resource
]
}
}, ...
]
}
This will cache any font we include in our app and that will be cache by a service worker.
Cache API Endpoints
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [...],
"dataGroups": [
{
"name": "restapiexample dummuy API",
"urls": ["http://dummy.restapiexample.com/api/v1/employees"],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 20,
"maxAge": "12h",
"timeout": "5s"
}
}
]
}
Data Groups – Cache Config
name
: Name of API Group.urls
: Array of API endpoints to be cached.strategy
: "freshness"
caching strategy. It will check the API status or network first then it will fallback to the service worker cache.maxSize
: The number of responses that going to be cached.maxAge
: How long the cache response is valid.timeout
: Conjunction with the strategy freshness value.
Update Cache
When you integrate the PWA the cache data is started to load even if you refresh the browser or even if you rebuild the angular application.
To avoid that we can use the SW update provided by the angular service worker library it will allow us to determine if there is an update that needs to be pushed.
import { Component } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
...
export class AppComponent {
constructor(private swupdate: SwUpdate) {
// checks if update available
this.swupdate.available.subscribe((event: any) => {
// reload / refresh the browser
this.swupdate.activateUpdate().then(() => document.location.reload());
});
}
}