多个命名的路由器出口-导入但未初始化和呈现的组件

Adr*_*net 7 javascript router-outlet angular angular-router angular8

router-outlet在网络应用中使用多个命名为angular 8的名称。所有routerLink似乎都可以使用,因为它更改了URL,但是第二个router-outlet中的组件已导入,但未初始化也未呈现。


我在这里提供了Stackblitz:https ://stackblitz.com/edit/ng-multiple-router-outlet?file = src/app/app.component.ts

如您所见,当您单击侧边栏时,在照片下方,您可以通过单击Google或Facebook进入第二级导航,但不会呈现任何内容。

在模块中,可以很好地导出其他模块和RouterModule中使用的组件,以使其易于访问,我看不出我做错了什么。

我试图同时使用forRootforChild方法来声明路由,放置了一些日志,但是没有足够的线索。

谢谢你的帮助 !

yur*_*zui 7

一旦您了解了嵌套路由的工作原理,Angular 路由器就非常简单。

让我们想象一个简单的配置:

RouterModule.forRoot([
  { 
    path: '',
    component: HomeComponent,
    children: [
       { path: 'child', component: ChildComponent }
    ]
  }
])
Run Code Online (Sandbox Code Playgroud)

您将如何使用router-outlet覆盖上述所有路线?

app.component.html
     \
   contains
       \
    <router-outlet></router-outlet>
                 \/
             renders
                  \
              HomeComponent
             home.component.html
                  \
               contains
                    \
               <router-outlet></router-outlet>
                   renders
                       \
                     ChildComponent
Run Code Online (Sandbox Code Playgroud)

这里的主要内容是router-outlet根据路由器上下文渲染组件。一旦它呈现组件,就会创建一个新的上下文,并且所有router-outlet在此级别声明的都将查看children配置。

命名路由也是如此。

您已生成如下链接:

(selection:facebook//sidebar:photos)
Run Code Online (Sandbox Code Playgroud)

这意味着这些命名路由应该在相同的根级别。但是您<router-outlet name="selection"></router-outlet>在 router 呈现的嵌套级别定义了LibraryComponent

让我们在与“侧边栏”相同的级别添加这个插座:

<router-outlet name="sidebar"></router-outlet>
<router-outlet name="selection"></router-outlet>
Run Code Online (Sandbox Code Playgroud)

它实际上有效stackblitz


现在让我们回到你的尝试。如果你想在里面渲染选择组件,selection.component.html那么你应该使用嵌套的命名路由链接:

选择.component.html

[routerLink]="['.', { outlets: { selection: [routeName] } }]"
                \/
           relative path
Run Code Online (Sandbox Code Playgroud)

上述绑定将生成嵌套链接,如 (sidebar:photos/(selection:facebook))

现在您需要将SelectionRoutes配置移动到路径children属性photos

selection.module.ts

imports: [
  CommonModule,
  RouterModule, //.forChild(SelectionRoutes)
],
Run Code Online (Sandbox Code Playgroud)

sidebar.routes.ts

import { SelectionRoutes } from '../selection/selection.routes';
...
export const SidebarRoutes: Route[] = [
  { path: 'photos', component: LibraryComponent, outlet: 'sidebar', children: SelectionRoutes },
Run Code Online (Sandbox Code Playgroud)

Stackblitz 示例

更新

为了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', },
]
Run Code Online (Sandbox Code Playgroud)

Stackblitz 示例