Angular 2 条路线在构建项目后不起作用

Angular 2 routes not working after building the project

这些是我的路线:

import { Routes } from '@angular/router';
import {WelcomeComponent} from "./welcome/welcome.component";
import { LoginComponent } from './login/login.component';

export const routes: Routes = [
  {path: '', component: WelcomeComponent},
  {path: 'login', component: LoginComponent},
  {path: '**', component: WelcomeComponent}
];

我使用 ng buid 构建我的项目。

当我输入一个未定义的路径时,我希望应用程序重定向到 '/' 路径,就像在开发过程中发生的那样,但我收到 404 错误。

即使我手动输入 /login URL.

也出现同样的错误

我错过了什么?

如果你想重定向,你应该准确指定:

  { path: '**', redirectTo: '/'}

不过,我推荐这样的东西:

  {path: '/welcome', component: WelcomeComponent},
  {path: '/login', component: LoginComponent},
  {path: '**', redirectTo: '/welcome'}

还要注意路径中的前导斜杠。

您需要确保您的应用程序是通过快速服务器还是任何其他网络服务器提供服务,您应该将所有获取请求重定向到 index.html

只要您的服务器没有将所有请求重定向到 index.html,您的 Angular 应用中发生的事情并不重要。

正如@Milad 所说,我必须将所有获取请求重定向到 index.html。 添加 .htacces 文件解决了我的问题:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.html [L]
</IfModule>

对我来说,当我将构建命令从 ng build 更改为 ng build --prod 时,问题得到解决。当然,当您需要构建在生产环境之外运行时,您不能使用此解决方案。