Angular懒加载路由问题求助:从/customers重定向到/customers/detail失败
Hey there! I see you're new to Angular and stuck with a routing redirect problem in your lazy-loaded module. Let's break down the issue and fix it step by step.
The Problem
You want to redirect from /customers to /customers/detail, but you're hitting the error Cannot match any routes. URL Segment: 'detail'. The root issue lies in how your child routing module (customer-routing.module.ts) is configured right now.
The Solution
Modify your customer-routing.module.ts to handle the redirect directly within the lazy-loaded module's routing setup. Here's the updated code:
// customer-routing.module.ts const routes: Routes = [ // Redirect the empty path (maps to /customers) to /customers/detail { path: '', redirectTo: 'detail', pathMatch: 'full' }, { path: 'detail', component: CustomerDetailComponent }, ];
Why This Works
- The
path: ''in the child routing module corresponds to the parent lazy-loaded path/customers(since thecustomersroute inapp-routing.module.tsusesloadChildrento mount this module's routes under/customers). redirectTo: 'detail'uses a relative path, so it will correctly navigate to/customers/detail.pathMatch: 'full'ensures the redirect only triggers when the path exactly matches/customers—this prevents partial matches from interfering with any future child routes you might add.
If you ever need to keep CustomersComponent as a parent container (with a <router-outlet> for child routes), you could adjust the setup like this instead:
// customer-routing.module.ts const routes: Routes = [ { path: '', component: CustomersComponent, children: [ { path: 'detail', component: CustomerDetailComponent } ] }, ];
Then add a redirect in CustomersComponent using the Router service:
import { Router, ActivatedRoute } from '@angular/router'; constructor(private router: Router, private route: ActivatedRoute) {} ngOnInit() { this.router.navigate(['detail'], { relativeTo: this.route }); }
But for your current goal of a direct redirect from /customers to /customers/detail, the first solution is the cleanest and simplest approach.
内容的提问来源于stack exchange,提问作者john chan

