Search code examples
angulartypescripthttp-status-code-404reload

Handle F5 reload in Angular


I have problem with my angular project. In dev (ng s) is working normally and after pressing F5 key, page reload correctly and working fine.

When I build and deploy project to remote server, everything is working fine, but after pressing F5 button, page reloads and show error 404 - not found. What I am doing wrong?

My router module:

const routes: Routes = [
  // hlavní cesty routingu
  { path: "login", component: LoginComponent },
  { path: "registration", component: RegisterComponent },
  { path: "resetPassword", component: ResetPasswordComponent },
  { path: "resetPasswordNew", component: InsertNewPasswordComponent },

  {path: "system",
  component: MainComponentComponent, 
  canActivate: [AuthGuard], // Auth guard mi vrací true nebo false podle toho, zda už mám načtený token nebo ne
  children: [ 
    { path: 'dashboard', component: DashboardComponent, canActivate: [RoleGuardService]},  //RoleGuardService mi hlídá, zda je lognutý žák nebo učitel
    { path: 'baterie'  , component: BaterieComponent},
    { path: 'settings' , component: SettingsComponent,
    children: [
      {path: 'info' , component: InfoComponent, canActivate: [RoleGuardService]}
    ]
    },
    { path: '', redirectTo: 'dashboard', pathMatch: 'full', },
  ]
  },

  { path: '', redirectTo: 'login', pathMatch: 'full', },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Thank you!


Solution

  • You should read Angular - Deployment documentation.

    Routed apps must fallback to index.html

    Angular apps are perfect candidates for serving with a simple static HTML server. You don't need a server-side engine to dynamically compose application pages because Angular does that on the client-side.

    If the app uses the Angular router, you must configure the server to return the application's host page (index.html) when asked for a file that it does not have.

    A routed application should support "deep links". A deep link is a URL that specifies a path to a component inside the app. For example, http://example.com/heroes/42 is a deep link to the hero detail page that displays the hero with id: 42.

    There is no issue when the user navigates to that URL from within a running client. The Angular router interprets the URL and routes to that page and hero.

    But clicking a link in an email, entering it in the browser address bar, or merely refreshing the browser while on the hero detail page — all of these actions are handled by the browser itself, outside the running application. The browser makes a direct request to the server for that URL, bypassing the router.

    A static server routinely returns index.html when it receives a request for http://example.com/. But it rejects http://example.com/heroes/42 and returns a 404 - Not Found error unless it is configured to return index.html instead.