Angular 5嵌套路由配置咨询:路由链接与定义匹配问题
Hey there, let's work through your Angular 5 nested routing issues clearly!
Core Issue: Mismatch Between Router Links and Route Definitions
First off, your <a routerLink="/price">Price</a> link doesn't align with your route configuration. The route you defined for Price is path: 'price/:priceId'—this requires a priceId parameter to be passed, but your current link doesn't include any parameter. That's why you're seeing a mismatch.
Fixes & Recommendations
1. Update Router Links to Include Required Parameters
If your PriceComponent depends on the priceId parameter to function, you need to pass that parameter in your router link. Use the array syntax for routerLink to pass dynamic values:
<ul> <li><a routerLink="/dashboard">Dashboard</a></li> <!-- Replace `somePriceId` with your actual variable/value --> <li><a [routerLink]="['/price', somePriceId]">Price</a></li> </ul>
In your component class, define the somePriceId variable (e.g., somePriceId = 101; for a static value, or fetch it from a service/API).
2. Add a Fallback Route for /price (If Needed)
If you want users to access /price without a parameter (e.g., to load a default view), add a dedicated route that redirects to a default priceId or loads a separate component:
const routes: Routes = [ { path: 'dashboard', component: DashboardComponent }, { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, // Fallback for /price without parameter { path: 'price', redirectTo: '/price/default', pathMatch: 'full' }, { path: 'price/:priceId', component: PriceComponent, children: [ { path: '', redirectTo: 'kpi', pathMatch: 'full' }, { path: 'kpi', component: DashboardComponent } // Make sure this is properly closed ] } ];
3. Ensure Nested Routes Can Render
For the child route (kpi) to load inside PriceComponent, you must add a <router-outlet></router-outlet> in the PriceComponent template. Without this, the child DashboardComponent won't be displayed.
4. Clean Up Incomplete Route Config
Your provided route snippet cuts off at {path: 'kpi', component: DashboardComponent...—make sure this route is fully defined (no trailing ellipses) to avoid parsing errors.
Quick Recap
The main problem is your router link doesn't supply the required priceId parameter for the price/:priceId route. Choose either to pass the parameter in the link, or add a fallback route for /price if you need a parameter-less entry point. Don't forget the <router-outlet> in your parent component for nested routes to work!
内容的提问来源于stack exchange,提问作者Dinesh Jain

