2
votes

Trying inside component programmatically navigate to another route path, but have error (ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment:).

Have next structure of 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]
      }],
  }
];

in main.module.ts in imports section:

@NgModule({
  imports: [
    ...............
    RouterModule.forChild(mainRoutes)
  ],

and 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>

Navigation from template working well (we switches on /qa/documents ), but when trying to navigate programmatically there we have error.

Just for testing trying to navigate in ngOnInit() hook method of milestone.component.ts:

export class MilestoneComponent implements OnInit {

  constructor( private router: Router) {}

  ngOnInit() {
    this.router.navigate(['/home/documents']);
  }

Have the Error: core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home/documents'

What may be the problem?

2
Please post how you declared your routes into your modules.user4676340
Also, feel free to make a minimal reproducible example.user4676340
Posted example of declaring of routes into modules.user2542456
If the routes are children, then you can't navigate to it with an absolute path, try setting them as root routes.user4676340
Ok, change RouterModule.forRoot(milestoneRoutes) and RouterModule.forRoot(mainRoutes), but there are next error takes place: Error: Uncaught (in promise): Error: RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.user2542456

2 Answers

2
votes

You should try to navigate with separate parameters in an array maybe:

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

You need to use the method navigateByUrl, like

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

See https://angular.io/api/router/Router#navigatebyurl