如何在Angular 4中进行路由。

13

我有一个 Angular 4 项目,当我从 localhost:4200/route-a 运行它时,它可以正常工作,当我刷新浏览器时,一切都按预期运行。然而,当我使用 ng build 构建它并从 Apache 运行时,导航到 localhost/route-a 返回一个 404 错误。以下是我的路由代码:

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

你需要配置你的 Apache 服务器以允许使用 HTML5 路由。 - Pankaj Parkar
因为这不是像服务器一样的路由:它是加载HTML模板的路由。如果你想让它工作,你必须设置你的服务器重定向到你做的每一个路由。 - user4676340
谢谢大家,让我试一下。 - Wafula Samuel
3个回答

36
这不是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将返回404错误。
但是通过告诉Apache,在任何请求的位置或文件不存在时,发送您的Angular HTML文件,Angular路由器将从那里接管。

8

4
有时您可能无法访问服务器配置。还有另一种可能的解决方案。
RouterModuleimport 中,有以下类似内容:
RouterModule.forRoot( routes )

您可以通过以下方式添加useHash
RouterModule.forRoot( routes, { useHash: true } )

然后使用生产标志重新构建您的项目,现在URL将会变成:

http://yourserver/#/page1/

这样,由于哈希的作用,应用程序将不会出现任何问题,唯一需要做的是在RouterModule上设置useHash并重新构建应用程序。

重写规则很好,但我认为拥有更多选项是好的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接