我在网络应用程序中使用多个命名的 angular 8 router-outlet
。所有 routerLink
似乎都有效,因为它更改了 URL,但我的第二个 router-outlet
中的组件已导入但未初始化或呈现。
我在这里提供了 Stackblitz:https://stackblitz.com/edit/ng-multiple-router-outlet?file=src/app/app.component.ts
如您所见,当您点击侧边栏时,在照片下您可以通过点击 Google 或 Facebook 获得第二个导航级别,但不会呈现任何内容。
在模块中,其他模块和 RouterModule 中使用的组件被很好地导出以供访问,我看不出我做错了什么。
我试图用 forRoot
和 forChild
方法声明路由,我放了一些日志,但我已经没有线索了。
感谢您的帮助!
最佳答案
一旦您了解了嵌套路由的工作原理,Angular 路由器就非常简单。
让我们想象一个简单的配置:
RouterModule.forRoot([
{
path: '',
component: HomeComponent,
children: [
{ path: 'child', component: ChildComponent }
]
}
])
您将如何使用 router-outlet
覆盖以上所有路线?
app.component.html
\
contains
\
<router-outlet></router-outlet>
\/
renders
\
HomeComponent
home.component.html
\
contains
\
<router-outlet></router-outlet>
renders
\
ChildComponent
这里的主要内容是 router-outlet
根据路由器上下文呈现组件。一旦它呈现组件,就会创建一个新的上下文,并且所有 router-outlet
在此级别声明的将查看 children
配置。
命名路由也是如此。
您生成的链接如下:
(selection:facebook//sidebar:photos)
这意味着这些命名路由应该处于相同的根级别。但是你定义了<router-outlet name="selection"></router-outlet>
在由路由器渲染的内部嵌套级别 LibraryComponent
.
让我们在与“侧边栏”相同的级别添加这个 socket :
<router-outlet name="sidebar"></router-outlet>
<router-outlet name="selection"></router-outlet>
它确实有效 stackblitz
现在让我们回到您的尝试。如果要在 selection.component.html
内渲染选择组件那么你应该使用嵌套的命名路由链接:
selection.component.html
[routerLink]="['.', { outlets: { selection: [routeName] } }]"
\/
relative path
上述绑定(bind)将生成嵌套链接,如 (sidebar:photos/(selection:facebook))
现在你需要移动SelectionRoutes
配置为 children
photos
的属性(property)路径:
selection.module.ts
imports: [
CommonModule,
RouterModule, //.forChild(SelectionRoutes)
],
sidebar.routes.ts
import { SelectionRoutes } from '../selection/selection.routes';
...
export const SidebarRoutes: Route[] = [
{ path: 'photos', component: LibraryComponent, outlet: 'sidebar', children: SelectionRoutes },
更新
为了制作facebook
作为默认子路由,您创建一个带有 redirectTo
的路由选项如:
export const SelectionRoutes: Route[] = [
{ path: 'facebook', component: FacebookComponent, outlet: 'selection' },
{ path: 'google', component: GoogleComponent, outlet: 'selection' },
{ path: '', redirectTo: '/(sidebar:photos/(selection:facebook))', pathMatch: 'full', },
]
关于javascript - 多个命名路由器导出 - 组件已导入但未初始化和呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57431200/