Lazy Loading
Lazy loading is frequently used to increase performance when developing large Angular applications. Lazy loading is the process of loading a module only after the user has navigated to its path. This shortens the app's initial load time.
We had a dashboard module that was lazy-loaded in one of our projects. When using the app, the module operated without any issues. However, a blank page or 404 error was displayed when the user reloaded the browser while on the dashboard route (such as http://localhost:4200/dashboard).
Reasons for the Problem
Angular routing is client-side. The browser requests that the server retrieve that route when you hit refresh, but the server is unaware of this.
How We Fixed It?
In order to allow Angular to manage the routing, we fixed it by setting the server to reroute all requests to index.html. Since we were using an Apache server in this instance, we updated the .htaccess file with the following:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
There is no issue if you use the built-in dev server in Angular CLI, as it takes care of this already. However, the hosting server needs to know for production.
Conclusion
App performance is enhanced by lazy loading, but if the server is not set up correctly, it may result in unforeseen problems. To allow Angular to handle routing, always ensure that your server reroutes unknown routes to index.html.