Angular 17 404 Throwing Error After Page Refresh

977 Views Asked by At

after I build my Angular 17 project and upload it to hosting, when I press F5 on my page, it redirects to a 404 page. I couldn't solve this situation in Angular 17.

I can view the component I crossed out without any problems, but when I press F5 on that page, it sends me to the 404 page.

According to the resources I researched, I was supposed to use LocationStrategy and HashLocationStrategy, but I didn't know how to use it with Angular 17.

screenshots:

app.routes.ts app.routes.ts

app.config.ts

app.config.ts

3

There are 3 best solutions below

1
On

With Angular 17, you can define your LocationStrategy in two ways...

  1. PathLocationStrategy

This is the Default strategy and relies on setting up the application's <base href> found in index.html

// App in root
<base href="/">

// App in sub-directory
<base href="/path/to/app/">
  1. HashLocationStrategy

This alternative strategy leverages the somewhat dated practice of adding a "#" to the URL for determining client updates and can be set by adding withHashLocation() to the app's provided router in app.config.ts

export const appConfig: ApplicationConfig = {
    providers: [provideRouter(routes, withHashLocation()), ...]
};

You can find more on LocationStrategy via the Angular 17 Docs... https://angular.dev/guide/routing/common-router-tasks#locationstrategy-and-browser-url-styles

0
On

You need to redirect to home component in the Routes

{ path: 'home', component: HomeComponent }, { path: '', redirectTo: '/home', pathMatch: 'full' },

0
On

This is a result of using a static site host. You'll need to use a NodeJS or other type of dynamic server such as Nginx or Apache to tell the server how to handle dynamic pages of your application.

If you can initially load your webpage and click to the pages, but get a 404 on refresh or while using a bookmarked URL, this is very most likely the issue.