我是 Angular 2 的新手。我想为我的应用程序的每个部分创建独立的模块。例如,我使用默认组件创建了 AuthModule
- AuthComponent
,其中包含用于其子组件(SignIn 或 SignUp)的 router-outlet
。所以我想实现以下场景:
- 当导航到/- root off app - 重定向到/auth
- 重定向到/auth 后 - 使用路由器导出加载 AuthComponent
- 加载 AppComponent 后 - 通过重定向到/auth/sign-in 加载默认登录组件
但是当我转到 localhost/时,我得到了我想要的重定向到/auth,但是下一个登录重定向没有出现。
我的代码:
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>
结果:
Environment @angular/cli: 1.0.0-rc.2 node: 7.7.1 os: win32 x64
最佳答案
我也遇到了同样的问题。这似乎是一个 Angular 技巧: 如果您删除“redirectTo”字段中的前导斜线,您的应用程序将成功重定向到 auth/sign-in。
在 app.routing 中使用它:
const routes: Routes = [
{path: '', redirectTo: 'auth', pathMatch: 'full'},
];
“redirectTo”值以“/”= 绝对路径开头
‘redirectTo’ 值以没有‘/’ = 相对路径的方式开始
阅读更多相关信息:https://vsavkin.com/angular-router-understanding-redirects-2826177761fc
P.S 我认为你的结构比 YounesM 的结构更正确。父模块不能保留子路由:“app”模块不知道“auth”模块有子模块“sign-in”。
关于Angular 2路由重定向到子路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42874859/