You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Angular 4多路由出口子路径匹配失败问题求助

解决Angular 4多路由出口的路由匹配问题

Hey there, let's tackle this routing issue you're facing with multiple outlets in your Superuser view. The error "Cannot match any routes" happens because the URL format you're using doesn't align with how Angular handles named router outlets. Here's what's going wrong and how to fix it:

问题根源

When you visit http://localhost:4200/superuser/contexts, Angular is looking for a unnamed child route called contexts under superuser, but your routing config defines contexts as a route tied specifically to the superuser-content outlet. Angular requires a special URL syntax for named outlets to distinguish which route goes to which outlet.

解决方案

1. 使用正确的URL格式访问多出口路由

For multiple named outlets, you need to use the parentheses syntax to specify which route maps to which outlet. To load both the SideMenuComponent (in superuser-sidemenu) and ContextsComponent (in superuser-content), your URL should look like this:

http://localhost:4200/superuser(superuser-sidemenu:)(superuser-content:contexts)
  • superuser-sidemenu: specifies the empty path route for the sidebar outlet
  • superuser-content:contexts specifies the contexts path for the content outlet

2. 在模板中生成正确的路由链接

Instead of manually typing the URL, use Angular's routerLink directive to generate the correct path in your templates. For example, if you want to add a navigation link in your SideMenuComponent to the contexts view:

<a [routerLink]="[{ outlets: { 'superuser-sidemenu': '', 'superuser-content': 'contexts' } }]">
  View Contexts
</a>

3. 优化路由配置(可选)

If you want to set a default component for the content outlet when visiting /superuser without any additional path, add a default route for the superuser-content outlet:

export const routes: Routes = [
 { path: "home", component: HomeComponent },
 { path: "superuser", component: SuperuserComponent, children:[
 { path: "", component: SideMenuComponent, outlet: 'superuser-sidemenu' },
 { path: "", component: DefaultContentComponent, outlet: 'superuser-content' }, // 新增默认内容组件
 { path: "contexts", component: ContextsComponent, outlet: 'superuser-content' }
 ] },
 { path: "", redirectTo: "/home", pathMatch: "full" }
]

This way, visiting http://localhost:4200/superuser will load both the sidebar and the default content component automatically.

验证修改

After updating the URL format or using routerLink correctly, you should no longer see the route matching error, and both the sidebar menu and contexts content will load in their respective outlets.

内容的提问来源于stack exchange,提问作者Iosif Bancioiu

火山引擎 最新活动