简体   繁体   English

Angular 2子路由

[英]Angular 2 child routing

I am trying to figure out why my child route is not being found: 我试图弄清楚为什么找不到我的孩子路线:

So I have a router that looks something like this: 所以我有一个看起来像这样的路由器:

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AboutComponent } from './about.component';
import { AboutTestComponent } from './about-test.component';
import { AboutSectionComponent } from './about-section.component';

const aboutRoutes: Routes = [
  {
    path: 'about',
    component: AboutSectionComponent,
    children: [
      {
        path: '',
        component: AboutComponent
      },
      {
        path: 'test',
        component: AboutTestComponent
      }
    ]
  }
];

export const aboutRouting: ModuleWithProviders = RouterModule.forChild(aboutRoutes);

In my about-section.component.html , I have the following mark-up: 在我的about-section.component.html ,我有以下标记:

<!-- some layout stuff here -->
<router-outlet></router-outlet>
<!-- more layout stuff -->
<button routerLink="/test"></button> <!-- I want to load the AboutTestComponent in the router outlet tags when I click on it -->

I want to be able to load the AboutTestComponent in the router-outlet of about-section.component.html because I want to reuse the HTML layout. 我希望能够在about-section.component.html的路由器出口中加载AboutTestComponent,因为我想重用HTML布局。 Right now when I land onto the "about" route, I get the expected AboutComponent, but when I click on the button trying to navigate to the "test" route, I get a 404. Is there a way to make the "test" route accessible using the way I am doing it now? 现在,当我进入“关于”路线时,我得到了预期的AboutComponent,但是当我单击尝试导航到“测试”路线的按钮时,我得到了404。是否有一种方法可以进行“测试”使用我现在的方式访问路由? If not, what would be a good way of approaching this problem? 如果没有,解决这个问题的好方法是什么?

I think this is only possible if you navigate to about/test with the following button: 我认为这只有在您使用以下按钮导航到about/test时才有可能:

<button routerLink="test"></button

I deleted the / before the test so it is a relative route. 我在test前删除了/ ,所以这是一条相对路线。

If you now click on the button it will navigate to about/test and the router loads the AboutTestComponent into the <router-outlet> of the parent. 如果现在单击按钮,它将导航至about/test ,路由器将AboutTestComponent加载到父级的<router-outlet>中。

You can also solve it with an absolute route: 您也可以使用绝对路线解决它:

<button routerLink="/about/test"></button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM