当前页面为http://localhost:4200/foo
。
情况 1:如果我按下浏览器的重新加载按钮或在浏览器中键入相同的 url,页面将重定向到 http://localhost:4200
(根路径)。
我希望该页面保持相同的 url (http://localhost:4200/foo
)。
情况 2:如果我键入 http://localhost:4200/foo
(相同的 url),页面将重定向到 http://localhost:4200
(根路径).
我还希望该页面保留我输入的相同 url (http://localhost:4200/foo
)。
否则,如果页面是 http://localhost:4200
并且我输入 http://localhost:4200/foo
,它工作正常。我可以正常通过 url 路径导航。只有当我走同一条路时才会出现问题。
我在 app.module.ts 中的根路径是:
const rootRouting: ModuleWithProviders = RouterModule.forRoot([
{
path: 'foo',
loadChildren: './foo/foo.module#FooModule'
},
{
path: '',
loadChildren: './bar/bar.module#BarModule'
},
], { });
我在 foo.module.ts 中的路径是:
const fooRouting: ModuleWithProviders = RouterModule.forChild([
{
path: 'foo',
component: FooComponent
}
]);
OBS:这个问题Angular 5 - redirect page to homepage on browser refresh想要的和我的正好相反。现在,我不知道这种情况下 Angular 的默认行为是什么。
DiPix修正后编辑:
我在 app.module.ts 中的根路径是:
const rootRouting: ModuleWithProviders = RouterModule.forRoot([
{
path: 'foo',
loadChildren: './foo/foo.module#FooModule'
},
{
path: '',
loadChildren: './bar/bar.module#BarModule'
},
], { });
我在 foo.module.ts 中的路径是:
const fooRouting: ModuleWithProviders = RouterModule.forChild([
{
path: '',
pathMatch: 'full',
component: FooComponent
}
]);
编辑 2:
使用 google chrome 调试,我设置了“保留日志”。
测试任何其他站点,如果您在“www.anydomain.com/path”并重新加载浏览器,chrome 会写入 “导航到‘www.anydomain.com/path’
。
使用我的应用程序进行测试,如果我在“http://localhost:4200/foo”并重新加载浏览器,chrome 会写入 “Navigated to 'http://localhost:4200/'
。
浏览器导航到根路径!
最佳答案
您需要在应用程序的根目录定义一些路由。像这样:
const routes: Routes = [
{ path: 'foo', component: FooComponent},
{ path: '', redirectTo: '/foo', pathMatch: 'full' },
{ path: '**', component: FooComponent }
];
这些路由将到达您定义 forRoot() 方法的位置,您的代码如下所示:
const rootRouting: ModuleWithProviders = RouterModule.forRoot(routes);
关于javascript - 浏览器重新加载时 Angular 4 重定向到根路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49019106/