user2542456
user2542456

Reputation: 111

angular navigate programmatically (router.navigate). Error: Cannot match any routes

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?

Upvotes: 5

Views: 8509

Answers (2)

You need to use the method navigateByUrl, like

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

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

Upvotes: 2

ForestG
ForestG

Reputation: 18105

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

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

Upvotes: 4

Related Questions