如何在 angular 中路由 4

How to route in angular 4

我有一个 angular 4 项目,当我从 localhost:4200/route-a 运行 它时,它工作正常,当我刷新浏览器时,一切都按预期工作。但是,当我使用 ng build 和 运行 从 apache 构建它时,导航到 localhost/route-a returns a 404。这是我的路由代码:

imports: [BrowserModule, HttpModule, FormsModule, RouterModule.forRoot([
    { path: 'home', component: HomeComponent },
    { path: 'route-a', component: RouteAComponent },
    { path: '', redirectTo: '/home', pathMatch: 'full' }
  ])]

这不是 Angular 问题。你的apache设置有问题。 当您在 Angular 中使用 HTML5 模式(漂亮 url)时,您将必须配置 Apache 以将服务器上不存在资源的所有请求发送到 index.html 文件.

这可以通过以下 .htaccess 配置来完成:

RewriteEngine On  
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

原因是当您尝试访问/route-a时,apache服务器会默认尝试查找目录route-a和其中的index.html文件。但是因为你没有那个目录,apache会return一个404错误。

但是通过告诉 apache,在任何位置或文件不存在的请求上。要发送已安装的 Angular html 文件,Angular 路由器会从那里获取它吗?

从 Apache 2.2.16 版开始,您可以为此使用 FallbackResource 指令:

<Directory "/var/www/my_blog">
  FallbackResource index.php
</Directory>

勾选https://httpd.apache.org/docs/trunk/rewrite/remapping.html#fallback-resource

有时您可能无法访问服务器配置。 还有另一种可能的解决方案。

RouterModuleimport 中有这样的东西:

RouterModule.forRoot( routes )

您可以这样添加 useHash

RouterModule.forRoot( routes, { useHash: true } )

然后使用生产标志重建您的项目,现在的 URL 将如下所示:

http://yourserver/#/page1/

这样,多亏了哈希,应用程序可以正常运行,唯一需要做的就是在 RouterModule 上设置 useHash 并重新构建您的应用程序。

重写规则很好,但我认为有更多选择也很好。