在 Angular 内处理 F5 重新加载

Handle F5 reload in Angular

我的 angular 项目有问题。在 dev (ng s) 中正常工作,按 F5 键后,页面重新加载正确并且工作正常。

当我构建项目并将其部署到远程服务器时,一切正常,但在按下 F5 按钮后,页面重新加载并显示错误 404 - 未找到。我做错了什么?

我的路由器模块:

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 { }

谢谢!

你应该阅读 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.