This content originally appeared on DEV Community and was authored by Kingsley Ubah
In this guide, we'll learn how to create an angular application with PWA features, making it act and feel like a progressive web application.
What is a Progressive Web App?
Progressive Web Apps, also known as PWAs are basically web applications enhanced to look and feel like native apps.
PWAs are configured to run on multiple devices using a single codebase. Thus once a progressive web app is deployed to the web, the app is also installable as a native application.
PWAs can be made to work offline using service workers; service workers can be used to cache and display content to a user even when the user is offline. No more error page with a dinosaur game.
Progressive Web Apps have been increasingly popular in the last couple of years as developers look for ways to increase the reach of their applications and improve user experience on their apps.
Setting Up an Angular Project with the Angular CLI
Let's install the Angular CLI and create a new Angular project with it.
As a prerequisite, you must have the latest versions of node.js and NPM (Node package manager) installed on your system to be able to install and use the Angular CLI.
At the time of writing, the current LTS version of node.js is v16.13.1. Head to the official website and grab the installers for your operating system.
Once you have the latest version of node.js installed, head over to a new command-line interface and run the following command to install the Angular CLI globally:
npm install -g @angular/cli
Next, let's create an angular app via the CLI using the following command:
ng new pwa-app
To configure your app, the CLI will first ask if you want to install the Angular router and then prompt you to select a stylesheet. You should install the router and select the default CSS for styling.
The ng new
command will create a workspace folder named pwa-app
and generate the angular materials and files inside of it.
If you are setting out with the intention of building a progressive app with Angular, you can just add the --service-worker
flag to the command, like so:
ng new pwa-app --service-worker
However, for the sake of learning, we'll go with the former approach so we can later add the service worker package using the ng add
command.
Once the folder is generated, run the ng build command to generate build files for your app:
ng build
Barring any issues, your app's final build files will be bundled into a directory named dist/
:
With the browser files ready, you can now serve your app by running the npm run start
script, this will in turn execute on the ng serve
command.
Follow the link provided on your command terminal and you will be directed to the starter page for your Angular project, hosted on http://localhost:4200/:
Please note that at this point, our app is not yet a progressive web app. You can check for this by inspecting your page’s HTML file using your browser's developer tool.
If you are on chrome, open your developer tool with cmd
+shift
+i
, click on the Application tab, and then navigate to the Service Workers tab. As shown below, our app has no registered service worker:
Now select the offline checkbox to simulate offline mode on your browser.
After simulating offline mode, go ahead and refresh the page. The following page will be displayed if you are on Google Chrome:
In the following section, we'll add the angular PWA library to our angular app using the ng add
command.
Adding Angular Service Worker with @angular/pwa
A service worker is a JavaScript file that is run by your browser in the background, separate from your web page, and handles events fired either by the browser or your webpage. Service workers can be used to make a web page work offline or to make the page perform well on slow networks.
Now that we have created an Angular project from scratch, let's turn it into a progressive web application.
Open your command terminal, then cd to your workspace folder and run the following command:
ng add @angular/pwa
This command will generate templates and files for your PWA. Here's the image of all generated files:
Once installation is complete, rebuild and serve your app with the following command:
ng serve
Follow the link to the browser and open the service worker tab on the developer tool just like before. This time you'll find a registered service worker file called ngsw-worker.js
:
You'll also find information about your PWA under the Manifest tab:
Thanks to caching from the service worker, your PWA will still be displayed even without an internet connection.
The manifest.webmanifest
and ngsw-config.json
files were generated as a result of adding the @angular/pwa
package.
Now let's take a brief look at these two files.
Customize your PWA with the Web App Manifest
Every PWA should have a web app manifest. The manifest.webmanifest
file found in the dist/pwa-app
folder contains information regarding the appearance and behaviour of your PWA.
{
"name": "pwa-app",
"short_name": "pwa-app",
"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"
},
// other icons
]
}
This includes the name for your app which will show up on the home screen, the theme and background colours, the URL which should be loaded when the application is launched, as well as the different icons for your app's use.
You can customize your app's properties by changing the values in the JSON object inside of the manifest.webmanifest
file.
Service worker configuration with ngsw-config.json
Another file generated by adding the angular PWA library is the ngsw-config.json
file, found in the root directory.
This config file is used to specify which files and data URLs the service worker should cache and how it should update the cached files and data. More detailed documentation on available configuration options can be found here.
Now let's take a look at how to use this file to cache resources and API endpoints for offline display.
Caching resources for offline use
Suppose you want to cache a set of fonts for offline use, you'll have to manually add a urls
entry for those resources inside the resources
object as follows:
// [...]
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/manifest.webmanifest",
"/*.css",
"/*.js"
],
"urls": [
"https://fonts.googleapis.com/css2?family=Roboto+Condensed:wght@700&display=swap"
// other resources goes here
]
}
},
// [...]
Here we are adding the Roboto font to be cached by the service worker. Every resource you add inside the array will be accessed by the PWA in offline mode.
Caching data from API endpoints for offline use
Within ngsw-config.js
, you can also cache data from API (Application Programming Interface) endpoints.
The dataGroups
field accepts an array of API groups which should be cached by the service worker.
Suppose our PWA displays the latest football results which it retrieves from an API endpoint. We can cache the API by inserting it into a dataGroups
array as follows:
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
// [...]
],
"dataGroups": [
{
"name": "football-results-api",
"urls": ["<https://api.footyresults.com/list>"],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 20,
"maxAge": "10min"
}
}
]
}
dataGroups
tells the service worker what APIs to cache for offline use.
Each API group is defined inside an object. In our example, we defined a name for our API using the name
property.
Under the url
property, we supplied the URL to the API that we want the service worker to cache. Since it is an array, we can pass in multiple URLs all of which will be under the same API name.
The final property is cacheConfig
, which has a value set to an object with some options. freshness
checks for the endpoint(s) before falling back to the service worker cache. maxSize
defines the maximum number of responses that the service worker should cache, and maxAge
defines how long the cache is valid for.
You can learn more about cache configuration options from the angular docs.
Without an internet connection, the PWA will show the last cached football results. After the user comes back online, the PWA will then pull the latest football results from the football results API.
Thus after 10 minutes, the list of results cached by the service worker will become invalid and as a result, a newer version of data will be cached from the API for offline display.
Update your PWA with SwUpdate
Whenever you deploy a new version of your PWA, it might take a while for the updates to reflect on the page.
For example, inside pwa-app/src/app/app.component.html
, if you change any text content, save the file, rebuild the app and then restart your server, it might take a while for your updates to reflect, though this depends on your cache policies.
This issue can be resolved using the SwUpdate
class from the Angular service worker library. SwUpdate
basically tells the service worker to update the PWA whenever an update is available.
Inside /src/app.component.ts
, we'll use swUpdate
to tell the service worker to check the http server for updates using the following code:
import { Component } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'pwa-app';
constructor( private readonly swUpdate: SwUpdate) {
if(this.swUpdate.available) {
this.swUpdate.available.subscribe(() => {
window.location.reload();
})
}
}
}
Here we create a constructor method on our app
component, passing in SwUpdate
as an argument. Inside the constructor method, we subscribe to an event with a callback function that triggers a page reload.
Save the file. Rebuild your app and view it on the browser. Now any updates you make will reflect on the browser.
Conclusion
Throughout this guide, we have walked through the process of creating a progressive web application with the Angular framework.
We have covered the manifest.webmanifest
file which is used for setting the metadata for a progressive web application. We also used the ngsw-config.js
to cache resources and API data for offline usage.
You can learn more about progressive web apps and service workers in Angular by reading the Service Worker and PWA guide from the official Angular documentation.
This content originally appeared on DEV Community and was authored by Kingsley Ubah
Kingsley Ubah | Sciencx (2022-01-18T14:51:51+00:00) How to Create a Progressive Web App with Angular. Retrieved from https://www.scien.cx/2022/01/18/how-to-create-a-progressive-web-app-with-angular/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.