Angular 2路由重定向到子路由 [英] Angular 2 routing redirect to with child routes
问题描述
我是Angular 2的新手。我想为我的应用程序的每个部分创建独立的模块。例如,我用默认组件- AuthComponent
创建了 AuthModule
,其中包含 router-out
表示其子组件(登录或注册)。所以我想实现以下情形:
I am a newbie in Angular 2. I want to create isolated modules for every part of my app. For example I created the AuthModule
with default component - AuthComponent
which contain a router-outlet
for his child components (SignIn or SignUp). So I want to realise the following scenario:
- 导航到/-退出应用程序-重定向到/ auth
- 重定向到/ auth后-使用路由器插座加载AuthComponent
- 加载AppComponent后-通过重定向到/ auth / sign-in加载默认登录组件
但是当我进入localhost /时,我可以重定向到/ auth我想要的东西,但是没有出现下一次重定向到登录的信息。
But when I going to localhost/ I get redirect to /auth what I want, but the next redirect to sign-in doesn't appear.
我的代码:
app.routing
const routes: Routes = [
{
path: '',
redirectTo: '/auth',
pathMatch: 'full'
}
];
export const appRouting: ModuleWithProviders = RouterModule.forRoot(routes);
auth.routing
const routes: Routes = [
{
path: 'auth',
component: AuthComponent,
children: [
{
path: '',
redirectTo: 'sign-in',
pathMatch: 'full'
},
{
path: 'sign-in',
component: SignInComponent
}
]
},
];
export const authRouting: ModuleWithProviders = RouterModule.forChild(routes);
auth.component.html
<div class="container">
<h1>Auth component</h1>
<router-outlet></router-outlet>
</div>
结果:
环境@ angular / cli:1.0.0-rc.2节点:7.7.1 os:win32 x64
Environment @angular/cli: 1.0.0-rc.2 node: 7.7.1 os: win32 x64
推荐答案
我遇到了同样的问题。似乎有一个Angular的把戏:
如果您在'redirectTo'字段中删除前导斜杠,则您的应用程序将成功重定向到auth /登录。
I have been the same problem. It seems an Angular tricks: If you remove leading slash in 'redirectTo' field, your application will be redirected successfully to auth/sign-in.
使用在app.routing中:
Use this in app.routing:
const routes: Routes = [
{path: '', redirectTo: 'auth', pathMatch: 'full'},
];
'redirectTo'值以'/'=绝对路径开头
‘redirectTo’ value starts with a ‘/’ = absolute path
'redirectTo'值开头时没有'/'=相对路径
‘redirectTo’ value starts without a ‘/’ = relative path
了解更多信息: https://vsavkin.com/angular-router-understanding-redirects-2826177761fc
PS我认为您的结构要比YounesM的结构更正确。父模块无法保留子路由:应用模块不知道身份验证模块具有子模块登录。
P.S My opinion that your structure more correctly then YounesM's one. Parent module can't keep children routes: "app" module don't know that "auth" module have children module "sign-in".
这篇关于Angular 2路由重定向到子路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!