I have a multi-module Angular 11 project and I am trying to implement routing.
Based on the documentation, I did this:
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{
path: 'articles',
loadChildren: () => import('./modules/articles/articles.module').then(m => m.ArticlesModule)
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
articles-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ArticleComponent } from './components/article/article.component';
import { ArticlesComponent } from './components/articles/articles.component';
const routes: Routes = [
{
path: '',
pathMatch: "full",
component: ArticlesComponent,
children: [
{
path: ':articleId',
component: ArticleComponent
}
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ArticlesRoutingModule { }
ArticlesComponent works as expected at localhost:4200/articles
, but when I try to open localhost:4200/articles/48451
to load ArticleComponent I get the following error:
Cannot match any routes. URL Segment: 'articles/48451' Error: Cannot match any routes. URL Segment: 'articles/48451'
CodePudding user response:
@Chaka15 is right in the meaning that you should have a <router-outlet></router-outlet>
inside your articles.component.html file.
In your routes configuration, you state that: ArticleComponent is a child of ArticlesComponent. In technical terms, it means that: when you access the route "localhost:4200/articles/48451", the router engine will first process the ArticlesComponent and then look for "<router-outlet></router-outlet>
" inside the articles.component.html
Here's the docs for that part https://angular.io/guide/router-tutorial-toh#child-route-configuration
CodePudding user response:
If you want to display the ArticleComponent
in a <router-outlet>
inside the ArticlesComponent
, you need to remove the pathMatch:"full"
otherwise it won't be able to match any children.
If both routes/components are independent, add two Routes instead of nesting them in children.
const routes: Routes = [
{
path: '',
pathMatch: "full",
component: ArticlesComponent
},
{
path: ':articleId',
component: ArticleComponent
}
];
cheers