以编程方式进行角度导航(router.navigate)。错误:无法匹配任何路由

时间:2018-03-21 09:23:35

标签: angular navigation router programmatically

尝试以编程方式在组件内导航到另一个路径路径,但有错误(错误错误:未捕获(在承诺中):错误:无法匹配任何路由.URL段:)。

有app的下一个结构:

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)
  ],

和milestoneRoute:

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
      }
    ]
  }
];

milestone.module.ts

    @NgModule({
      ..........
      RouterModule.forChild(milestoneRoutes)
      ],

milestone.component.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 ERROR错误:未捕获(在承诺中):错误:无法匹配任何路由。网址细分:&#39;主页/文档&#39;

可能是什么问题?

2 个答案:

答案 0 :(得分:1)

您应该尝试使用数组中的单独参数进行导航:

this.router.navigate(['home', 'documents']);

答案 1 :(得分:0)

您需要使用方法NavigationByUrl,例如

this.router.navigateByUrl('/home/documents')

请参阅 https://angular.io/api/router/Router#navigatebyurl