如何在角度4中布线 [英] How to route in angular 4

查看:79
本文介绍了如何在角度4中布线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an angular 4 project and when I run it from localhost:4200/route-a, it works fine and when I refresh the browser, all works well as expected. However, when I build it with ng build and run it from apache, navigating to localhost/route-a returns a 404. Here is my code for routing:

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文件.

It is not an Angular issue. It is a problem with your apache settings. When you are using HTML5 mode(pretty url) in Angular, you will have to config your Apache to send all request where the resource doesn't exist on the server to the index.html file.

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

This can be done with the following .htaccess configuration:

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

The reason is that when you try to access /route-a, the apache server will be default try to find the directory route-a and the index.html file within. But because you do not have that directory, will apache return a 404 error.

但是通过告诉apache,在任何请求中,位置或文件都不存在.要发送发送您的Angular html文件,请Angular路由器将其从那里接收.

But by telling apache, that on any request where the location or file do not exist. To send send your Angular html file indsted, will the Angular router take it from there.

这篇关于如何在角度4中布线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆