我正在尝试在我的角度应用程序中实现辅助路由,但由于某种原因,组件未显示,即使浏览器中的URL发生更改。
我的路线模块看起来像这样:
const routes: Routes = [
{ path: 'students', canActivate: [AuthGuard], component: StudentsComponent, outlet: 'main' },
{ path: 'login', component: LoginComponent },
{ path: '', canActivate: [AuthGuard], component: HomeComponent }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
HTML
的{{1}}模板基本归结为:
HomeComponent
所以,基本上当我在浏览器中打开<router-outlet></router-outlet>
<div class="">
<button [routerLink]="[{outlets: {main: ['students'] } }]">aux route</button>
<!-- <button [routerLink]="[{outlets: {main: ['/students'] } }]">aux route</button>
Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: '%2Fevents' -->
<router-outlet name="main"></router-outlet>
</div>
时,我可以看到我的辅助按钮,当我点击它时,浏览器中的网址将变为:http://localhost:4200
看起来不错,但http://localhost:4200/(main:students)
从未在页面上显示。
我想知道我做错了什么......
StudentComponent
只显示默认值:
StudentComponent
编辑:我正在添加一个显示问题的stackblitz链接。请注意第三个组件的内容从未显示过。
答案 0 :(得分:1)
我试图在stackblitz为你抢救一个例子。希望它有所帮助
应用路由
import { Routes, RouterModule } from '@angular/router';
import ComponentOne from './component-one';
import ComponentTwo from './component-two';
import ComponentAux from './component-aux';
export const routes: Routes = [
{ path: '', redirectTo: 'component-one', pathMatch: 'full' },
{ path: 'component-one', component: ComponentOne },
{ path: 'component-two', component: ComponentTwo },
{ path: 'component-aux',
component: ComponentAux,
outlet: 'sidebar'
}
];
export const routing = RouterModule.forRoot(routes);
应用组件模板
<nav>
<a [routerLink]="['/component-one']">Component One</a>
<a [routerLink]="['/component-two']">Component Two</a>
<a [routerLink]="[{ outlets: { 'sidebar': ['component-aux'] } }]">Component Aux</a>
</nav>
<div style="color: green; margin-top: 1rem;">Outlet:</div>
<div style="border: 2px solid green; padding: 1rem;">
<router-outlet></router-outlet>
</div>
<div style="color: green; margin-top: 1rem;">Sidebar Outlet:</div>
<div style="border: 2px solid blue; padding: 1rem;">
<router-outlet name="sidebar"></router-outlet>
</div>
答案 1 :(得分:1)
这是您的stackblitz的modified version,它似乎适用于这些路线:
const appRoutes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'first', component: FirstComponent },
{
path: 'second', component: SecondComponent,
children: [
{
path: 'third',
component: ThirdComponent,
outlet: 'third'
}
]
},
];
以及第二个组件的以下模板:
<a [routerLink]="[{ outlets: { third: ['third'] } }]">Aux third component</a>
<router-outlet name="third"></router-outlet>