Angular 5默认子路由未加载父组件问题求助
解决Angular 5默认路由重定向时父布局组件未加载的问题
看起来你的问题出在默认路由的重定向逻辑上——虽然你配置了从空路径重定向到home,但Angular 5在首次加载时可能没有正确触发父组件SiteLayoutComponent的渲染。我们可以调整路由配置的结构来解决这个问题:
调整后的路由配置
const appRoutes: Routes = [ // Site routes - 先绑定空路径到SiteLayoutComponent { path: '', component: SiteLayoutComponent, children: [ { path: '', redirectTo: 'home', pathMatch: 'full' }, // 在子路由里重定向到home { path: 'home', component: HomeComponent } ] }, // App routes goes here { path: 'app', component: AppLayoutComponent, children: [ { path: 'contact', component: ContactComponent } ] }, // No layout routes { path: '**', redirectTo: '' } // 重定向到空路径,会触发上面的SiteLayout逻辑 ]; export const routing = RouterModule.forRoot(appRoutes, { enableTracing: true });
为什么这样能解决问题?
原来的配置中,你是从空路径直接重定向到home路由,虽然home路由关联了SiteLayoutComponent作为父组件,但Angular在首次加载的路由解析流程中,可能没有先实例化父组件就直接渲染子组件了。
调整后的配置把空路径直接绑定到SiteLayoutComponent,这样首次加载空URL时,会先渲染包含导航栏的父布局,然后通过子路由的重定向规则加载HomeComponent到父布局的<router-outlet>中,完美符合你的预期。
额外检查点
- 确保你的根组件(比如
AppComponent)中存在<router-outlet>,因为SiteLayoutComponent是要渲染在这个根路由出口里的 - 保持
SiteLayoutComponent的代码不变,它的<layout-site-navbar>和内部的<router-outlet>是正确的结构
内容的提问来源于stack exchange,提问作者Junior Silva
相关产品推荐
相关产品推荐

