【问题标题】:Angular Router does not load my component despite correct URL尽管 URL 正确,Angular 路由器仍无法加载我的组件
【发布时间】:2019-08-11 09:59:23
【问题描述】:

我正在尝试使用我的路由器加载我的 Angular 组件,但它从未显示或引发错误。

应用路由模块

  { path: '', redirectTo: '/home', pathMatch: 'full' },
  {
    path: 'home', component: HomeComponent, children:
      [
        { path: 'compare', component: CompareComponent, children:[] },
        {
          path: 'settings', component: SettingsComponent, children: [
            { path: 'new', component: ServerConnectionEditComponent }
          ]
        },
      ]
  },

应用服务器连接

  constructor(private router:Router, private route:ActivatedRoute) { }
  onAddServer()
  {
    console.log(this.route.url)
    this.router.navigate(['new'], {relativeTo: this.route});
  }

该 URL 似乎有效,因为任何其他 URL 都会引发错误。

应用服务器连接编辑

  ngOnInit() {
    console.log("in Edit") //never gets here
  }

服务器连接.component.html

...
<th scope="col"><button type="button" class="btn btn-success btn-sm"
                  (click)="onAddServer()">+</button></th>

app-component.html

<app-header></app-header>
<div class="container">
  <div class="row">
    <div class="col-md-12"> 
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

settings.component.html

<div class="container">
  <div class="row">
    <div>
      <div class="col-md-12" >
        <h4>Server Connections:</h4>
      </div>
      <br/>
      <div class="col-xs-12">
          <app-server-connections [serverConnections]="serverConnections"></app-server-connections>
      </div>
    </div>
  </div>
</div>

【问题讨论】:

  • 您要导航到哪个网址?
  • &lt;router-outlet&gt; 的设置够了吗?请记住,当使用children 时,每个父组件都需要在其模板中添加一个&lt;router-outlet&gt;
  • 如果我添加 组件会立即加载,并且我希望它在按钮单击时加载。

标签: javascript angular typescript angular8


【解决方案1】:

您的路由中只能有 1 级嵌套子级。所以像这样改变你的路线。如果这不起作用打开浏览器控制台,看看它是否有任何错误

{
    path: 'home', component: HomeComponent, children:
    [
        { path: 'compare', component: CompareComponent },
        {
            path: 'settings/new', component: ServerConnectionEditComponent

        },
        { path: 'settings', component: SettingsComponent }
    ]
}

并确保添加&lt;router-outlet&gt;&lt;/router-outlet&gt; 在你的 app.component.html 中

【讨论】:

  • 现在它只加载我的 copmonent 而不是我的 ServerConnectionsComponent 而不是在它旁边。
  • settings.component.html &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div&gt; &lt;div class="col-md-12" &gt; &lt;h4&gt;Server Connections:&lt;/h4&gt; &lt;/div&gt; &lt;br/&gt; &lt;div class="col-xs-12"&gt; &lt;app-server-connections [serverConnections]="serverConnections"&gt;&lt;/app-server-connections&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; server-connections.component.html ``` ... ```
  • 只是更改路线顺序我只是更新我的答案
  • 谢谢!非常感谢
【解决方案2】:

更具体的必须排在不太具体的之前。因此,settings/new 必须在设置之前按顺序排列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 2017-09-03
    • 1970-01-01
    • 2016-06-18
    • 2016-07-20
    • 2017-07-21
    • 2016-12-25
    相关资源
    最近更新 更多