构建项目后,Angular 2路由无法正常工作

时间:2017-05-19 08:42:10

标签: angular angular2-routing

这些是我的路线:

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错误。

即使手动输入/登录URL,我也会收到同样的错误。

我错过了什么?

4 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:2)

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

只要您的服务器没有将所有请求重定向到index.html,您的Angular应用程序中发生的事情都无关紧要。

答案 2 :(得分:1)

如果要重定向,则应准确指定:

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

但是,我推荐的内容如下:

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

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

答案 3 :(得分:0)

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

相关问题