【问题标题】:Angular 4 - Child routes and using two route outletsAngular 4 - 子路线并使用两个路线出口
【发布时间】:2019-05-15 02:32:12
【问题描述】:

我已经在门户网站上阅读了所有与此相关的解决方案,但找不到合适的解决方案。事情是这样的:

我有一个组件:

import {Component} from '@angular/core';

@Component({
  selector: 'component-one',
  template: 'Component One'
})
export class ComponentOne { 

}

还有两个子组件:

import { Component } from '@angular/core';

@Component({
  selector: 'child-one',
  template: 'Child One'
})
export class ChildOne { 
}

import { Component } from '@angular/core';

@Component({
  selector: 'child-two',
  template: `

    <nav>
      <a [routerLink]="['child-one']">Child One</a><br />
      <a [routerLink]="['child-two']">Child two</a><br />
    </nav>
  <router-outlet></router-outlet>
  `
})
export class ChildTwo { 
}

当您单击 ComponentOne 路由时,我想要实现的是我被重定向到包含模板和另一个路由器出口的子二组件。

这就是路线的样子:

import { Routes, RouterModule } from '@angular/router';
import ComponentOne from './component-one';
import ComponentTwo from './component-two';
import ChildOne from './child-one';
import ChildTwo from './child-two';

export const routes: Routes = [
  { path: '', redirectTo: 'component-two', pathMatch: 'full' },
  { path: 'component-two', component: ComponentTwo },
  { path: 'component-one', component: ComponentOne,
    children: [
      { path: '', redirectTo: 'child-two', pathMatch: 'full' },
      { path: 'child-one', component: ChildOne },
      { path: 'child-two', component: ChildTwo }
    ]
  }
];

export const appRoutingProviders: any[] = [

];

export const routing = RouterModule.forRoot(routes);

在 app.component.html 我有:

import {Component} from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app',
  template: `
    <nav>
      <a [routerLink]="['/component-one']">Component One</a>
      <a [routerLink]="['/component-two']">Component Two</a>
    </nav>


    <div style="color: green; margin-top: 1rem;">Outlet:</div>
    <div style="border: 2px solid green; padding: 1rem;">
      <router-outlet></router-outlet>
    </div>
  `
})
export class AppComponent {

}

我遇到的错误是: 未捕获(承诺):错误:找不到加载“ChildTwo”的主要出口 错误:找不到加载“ChildTwo”的主要插座

有谁知道问题出在哪里?我在 child-two 组件和 app.component 中添加了路由器出口。

如果有人需要知道,这是应用程序的结构: 谢谢!

【问题讨论】:

  • 组件一中有路由器插座吗?
  • 在component-one中没有,只在child-two和app.component中
  • 这就是问题所在。你在你的路由器配置中说你的 ComponentOne 有孩子(子路由),但是没有模板可以渲染它。有时它本身不是问题 - 但你在那里有一个完整的重定向。
  • 您是否有 Stackblitz 或者只是简单的 HTML 示例来说明您想要实现的目标?
  • 亲爱的 Zlatko,非常感谢!你让我今天一整天都感觉很好。 :) 组件一中缺少路由器出口标签!这个例子来自教程,他们也错过了这个重要的事实......

标签: angular typescript angular-ui-router angular4-router


【解决方案1】:

正如评论中所解决的那样,您的 ComponentOne 需要一个 &lt;router-outlet&gt;。你在路由器配置中告诉 Angular ComponentOne 有子路由(子路由),但没有渲染它的出口。

有时您不会立即看到问题 - 但您在 '' 上有一个 fullRedirect,因此问题状态会立即触发。

简而言之,如果给定的路由配置有子节点,则该组件需要一个路由器出口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2017-07-28
    • 2014-01-10
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多