子路由的角度路由问题

时间:2019-02-12 13:47:29

标签: angular angular2-routing

我在用子组件正确编写父组件时遇到问题。当我路由到孩子时,似乎也在重新创建父对象,这导致html翻了一番。

您可以在我创建的here的stackblitz示例中看到这一点。

在我的应用程序的根目录中,我有一个配置组件:

@Component({
  selector: 'app-configuration',
  template: ` <app-sidebar></app-sidebar>
             <router-outlet></router-outlet>`
   })

然后它包含一个侧边栏组件,其中包含我希望浏览的链接列表。

@Component({
  selector: 'app-sidebar',
  template: `<div id="menu">
            <ul *ngFor="let gateway of gateways$ | async">
                <li><a routerLink="configure/{{gateway.toLowerCase()}}"> 
 {{gateway}}</a></li>
            </ul>
          </div>`
   })

export class SidebarComponent implements OnInit {

  gateways$:Observable<string[]>;
  constructor() { }
   ngOnInit() {
    this.gateways$ = this.getGateways()
   }
   getGateways():Observable<string[]>{
    let gateways=["CDS","MCP","CNS"]
    return of(gateways);       
}

问题的原因似乎是我如何定义路线:

const routes: Routes = [
  {
    path:'configure',component: ConfigurationComponent, 
    children:[
        {path:'cds', component: CdsComponent},
        {path:'mcp', component:McpComponent},
        {path:'cns', component:CnsComponent},
    ]
  }

有人可以告诉我是否有可能做我想做的事情,以及我做事的方式?我希望将子组件包含在配置组件中,这样我就可以将同级组件包含到配置中,以允许我做其他事情。

3 个答案:

答案 0 :(得分:2)

三个问题:

  1. app.component.ts模板中应为<router-outlet></router-outlet>而不是<app-configuration></app-configuration>

  2. sidebar.component.ts模板中应有<li><a routerLink="/configure/{{gateway.toLowerCase()}}">{{gateway}}</a></li>而不是<li><a routerLink="configure/{{gateway.toLowerCase()}}">{{gateway}}</a></li>

{p> /中缺少

routerLink

  1. 将您的路由配置更改为:

  const routes: Routes = [
  {
    path: 'configure', component: ConfigurationComponent,
    children: [
      { path: 'cds', component: CdsComponent },
      { path: 'mcp', component: McpComponent },
      { path: 'cns', component: CnsComponent },
    ]
  },
  {
    path: '**', redirectTo: '/configure', pathMatch: 'full'
  }
];

  

这是您推荐的Working Sample StackBlitz

答案 1 :(得分:1)

您正在混合组件和布线。

ASSOC中,您始终显示app.component.ts,因此它只显示一次。

然后继续进行路由,以便再次显示。

相反,在ConfigurationComponent中,模板应该只是app.component.ts,以便触发设置的路由器。

然后,您可以在<router-outlet></router-outlet>中使用configuration.component.ts`。

顺便说一句,您的template:位置不正确,应该为:

ngFor*

答案 2 :(得分:0)

尝试将重定向默认路由添加到您的子路由。

const routes: Routes = [
  {
    path:'configure',component: ConfigurationComponent, 
    children:[
        {path: '', redirectTo: 'cds', pathMatch: 'full'},
        {path:'cds', component: CdsComponent},
        {path:'mcp', component:McpComponent},
        {path:'cns', component:CnsComponent},
    ]
  }

在这些情况下使用默认路径真是很好

如果这不起作用,请提供完整的代码示例(带有完整的路由模块,而不仅仅是路由)

相关问题