尝试以编程方式导航到另一个路由路径的内部组件,但出现错误(错误错误:未捕获(承诺(:错误:无法匹配任何路由。网址段:(。
有下一个应用程序结构:
app.module.ts
main.module.ts
milestone.ts
const mainRoutes: Routes = [
{
path: '',
component: MainComponent,
canActivate: [LoggedInGuard],
children: [{
path: '',
component: ContentComponent
},
{
path: 'milestone/:milestoneId',
loadChildren: './content/milestone/milestone.module#MilestoneModule',
canActivate: [MilestoneGuard]
}],
}
];
在main.module.ts
imports
部分中:
@NgModule({
imports: [
...............
RouterModule.forChild(mainRoutes)
],
和里程碑路线:
const milestoneRoutes: Routes = [
{
path: '',
component: MilestoneComponent,
canActivate: [LoggedInGuard],
children: [{
path: '',
redirectTo: 'qa/documents',
pathMatch: 'full'
},
{
path: 'qa/documents',
component: qaDocumentsComponent
},
{
path: 'home/documents',
component: homeDocumentsComponent
}
]
}
];
里程碑.模块.ts
@NgModule({
..........
RouterModule.forChild(milestoneRoutes)
],
里程碑组件.html:
<div class="row content-wrap">
<sidebar></sidebar>
<main class="main-content">
<router-outlet></router-outlet>
</main>
</div>
从模板导航运行良好(我们打开/qa/documents
(,但是当尝试以编程方式导航时,我们遇到了错误。
仅用于测试尝试在 milestone.component.ts 的 ngOnInit(( 钩子方法中导航:
export class MilestoneComponent implements OnInit {
constructor( private router: Router) {}
ngOnInit() {
this.router.navigate(['/home/documents']);
}
有错误:core.es5.js:1020 错误错误:未捕获(承诺(:错误:无法匹配任何路由。网址细分:"首页/文档">
可能有什么问题?
您应该尝试使用数组中的单独参数进行导航:
this.router.navigate(['home', 'documents']);
你需要使用方法navigateByUrl,比如
this.router.navigateByUrl('/home/documents')
看https://angular.io/api/router/Router#navigatebyurl