The Solution
If you're struggling to deploy your Angular 7 app to GitHub pages, look no further than this helpful thread. It appears that the issue lies in the order of operations when it comes to routing in Angular. The official documentation touches on this in its section "Deploying to GitHub Pages", although it may not be explained as clearly as needed. In summary, you need to create a custom 404 error page (named 404.html
) that mirrors your compiled Angular root page, and place it in the output folder (e.g., /docs
) after compiling your Angular app. Do not put it in your source code folder; otherwise, the Angular compiler won't generate the necessary output for this workaround to function properly.
While there are more sophisticated solutions for other web hosting platforms, they aren't accessible on GitHub pages due to restrictions.
The Breakdown
Curious about why this issue occurs? Let's delve into the explanation:
Essentially, your Angular router operates within the root of your Angular application, activating once your app initializes. Your Angular app itself resides on the main page of your site.
Typically, when you request a URL, the server delivers the corresponding page. However, Angular is "single-page", meaning the additional "pages" defined by routes do not actually exist. Instead, Angular dynamically switches content within your app to simulate different "pages". These routes simply map which content should replace the current view depending on the URLs received by the Angular router. This distinction is crucial and ties back to the sequence of events.
When you access your app's root page, the server returns that page before the Angular app and router commence their processes. To handle any routed URLs, the Angular router must already be operational. Thus, initiating from the homepage first and then navigating via links succeeds because the server sent the root page, enabling the Angular router to intercept navigation requests post-startup. Nonetheless, requesting routed URLs directly from the server (including through a refresh) triggers a 404 error since those "pages" aren't tangible and aren't returned by the server.
The workaround addresses this limitation by ensuring the Angular router initializes consistently. By duplicating your home page as the 404 error page, you provide the server with an actual page to serve on encountering a 404 error. Consequently, any requested route will return either your genuine homepage or the duplicated 404 error page (mirroring the home page), guaranteeing the Angular router's activation and seamless navigation between "pages."