HOW TO FIX THE ROUTING ISSUE WITH PWAs BUILT WITH ANGULAR
In simple terms, PWAs are web applications that can function both online and offline. They are fast and still work fine under bad connectivity. They have a ‘native-app-like’ feel i.e they can be ‘installed’ on android, IOS and desktop platforms. Awesome! To read more about PWAs, visit the link below:
The angular team did a great job simplifying the development process of PWAs but there is an issue with it that I have noticed since version 5 and still existed till version 7. Not sure if it has been fixed in version 8. The issue, which I believe is a bug, prevents proper functionality of routing. This write up provides a guide on how to fix it. I am going to build a simple angular application from scratch, reproduce the error and fix it. Let’s get started!
- Create a new angular project as described below:
ng new angular-app
You can go with the defaults. You should get a ‘success’ message if everything goes right.
2. Navigate into the newly created project and create two new components — ‘page1’ and ‘page2’ by running the command below:
cd angular-app && ng g c page1 && ng g c page2
3. Modify app-routing.module.ts to be as described below:

run ‘ng serve’ to start the application.
Wow! Just noticed the default landing page has been redesigned.

Not bad :)
As much as I’d like to keep the dope page. I’m sorry I have to let it go :(
Modify app.component.html to be as below:

A little styling wouldn’t hurt. Would it?

Your application should look as attached below. Test and be sure both routes are working fine.

4. Now, we will enable offline functionality by running the command below.
ng add @angular/pwa
Yes! It’s that simple. Though you might need some other customisations as the case may be( check official docs). But in this case, we are fine.
5. PWA does not work in development mode in angular. Hence, we need to build the app and run on a server. I will be using MAMP in my case.
You should have something like this:

6. Run the app on your server of choice. If everything still works fine, go offline and reload the page. You should get a 504 error. That’s the error we are about fixing. If you are on chrome [why should you be on any other :) ], you can simulate offline mode as described below:

7. Run the command below to install ‘replace-in-file’ package:
npm install replace-in-file
8. In the root directory of your project, create a folder called ‘build’ , create a file ‘sw.js’ and paste the script below in it. Thanks to Jackoppa who wrote the script.
9. Modify ‘script’ object in ‘package.json’ as below:

Also modify the output path in angular.json so that your built app will now be in angular-app folder:

10. Finally, build the app again, but this time using the command ‘npm run custom-build’ as modifed in package.json earlier. Move to server and every route should be working fine, even when offline.
