Angular 2 从 URL 访问子路由

kts*_*gop 5 redirect routes angular

在我的主模块 (app.module) 中使用以下 Angular 2 Routes,我能够成功地浏览所有引用的组件视图。

const routes: Routes = [
    {path: '', redirectTo: 'home', pathMatch: 'full'},
    {path: 'home', component: HomeComponent},
    {path: 'other', component: OtherComponent},
    {path: 'extra', component: ExtraComponent},
    {path: 'group', component: GroupComponent,
        children: [
        {path: '', component: FirstPageComponent},
        {path: 'comp1', component: FirstPageComponent},      
        {path: 'comp2', component: SecondPageComponent},
        {path: 'comp3', component: ThirdPageComponent},
        {path: 'comp4', component: FourthPageComponent}
        ]
    },
    {path: '**', component: HomeComponent}
];
Run Code Online (Sandbox Code Playgroud)

另外,使用 LocationStrategy,这里描述: LocationStrategy and browser URL styles

我可以访问

http://localhost:3000/extra

通过直接在地址栏上输入它,因为路径被重定向到应用程序的根目录并由 Angular 的路由处理。

但我不能直接访问像

http://localhost:3000/group/comp2

这会产生 404 错误,因为请求的所有资源都从路径http://localhost:3000/group/ ... 开始,这是不正确的。

通过 RouterLink 指令的应用内导航工作正常。

任何意见,将不胜感激。

更新 :

看来问题不是由 Angular 路由机制或 Web 服务器配置引起的。即使重新加载或在地址栏中键入路径,路由也能正常工作,因为 lite-server 被配置为将所有路径重定向到 index.html。

问题是 index.html 正在使用相对路径加载一些脚本和样式表,就像我的一个组件(加载配置文件)一样。

所以当重新加载/输入路径时

http://localhost:3000/group/comp2
Run Code Online (Sandbox Code Playgroud)

服务器确实重定向到试图访问的 index.html,例如:

<script type="text/javascript" src="assets/vendor/bootstrap/js/bootstrap.min.js" ></script>
Run Code Online (Sandbox Code Playgroud)

但完整的 src 路径现在变成了:

src = "group/assets/vendor/bootstrap/js/bootstrap.min.js"
Run Code Online (Sandbox Code Playgroud)

哪个不存在。

我可以使用绝对路径来解决这个问题,但是由于我的生产环境未确定并且应用程序的根路径未知,所以这是不可能的。

我一直试图找到一种方法在运行时确定应用程序的根路径并使 src=".." 链接动态但无法解决,所以我决定编辑我的路由,以便它们都是兄弟他们都没有子路线。

感谢您的帮助,对于对问题的误解深表歉意。

Ant*_*ijo 2

与之前相同,您需要将后备配置为angular2 文档中描述的 index.html