angular - 如何以 Angular 4 路由

标签 angular apache angular4-router

我有一个 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' }
  ])]

最佳答案

这不是 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 路由器会从那里获取它。

关于angular - 如何以 Angular 4 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44819308/

相关文章:

Angular 2 : open ng2-bootstrap modal from parent component

php - 如何让 Xdebug 为 php 7.3 和 apache (MACOS) 工作

python - 或者在 Elasticsearch 过滤器中

mysql - Sqoop使用Java API导入Hbase表

angular - 当用户使用 f5 重新加载页面时,如何以 Angular 正确进行?

javascript - 未捕获( promise ): SecurityError: Failed to execute 'pushState' on 'History'

javascript - Angular 2重新渲染表单

css - mydaterangepicker 和 primeng 的问题,它在表头中显示错误,有人可以帮我吗

javascript - Angular2指令修改点击处理

html - 路由 Angular 4/5 隐藏组件