问题描述
我仍然习惯于Angular以及如何正确构造不同的组件和模块。我想根据最佳做法设置我的应用程序,并最大程度地提高效率。我目前有多个模块。我有一个要导航到的“基本”模块,但是根据URL,我希望合并其他模块中的组件。这是我的app-routing.module当前设置的方式:
const routes: Routes = [
{ path: '',component: BaseComponent },{ path: 'featureone',loadChildren: () => import('./feature-one/feature-one.module').then(m => m.FeatureOneModule) },{ path: 'featuretwo',loadChildren: () => import('./feature-two/feature-two.module').then(m => m.FeatureTwoModule) },{ path: '**',redirectTo: '',pathMatch: 'full'}
];
我了解此路由设置不正确,但是我不确定如何以最有效的方式正确设置此路由。
当前,如果我导航到''
,它将按预期加载BaseComponent。如果我加
<app-feature-one></app-feature-one>
要么
<app-feature-two></app-feature-two>
到BaseComponent模板,它将引发诸如“初始化前无法访问'FeatureOneModule'之类的错误”
是否可以通过某种方式将诸如“ featureone”和“ featuretwo”之类的路由保留到导航至BaseComponent的位置,并且可以添加逻辑以显示<app-feature-one></app-feature-one>
要么
<app-feature-two></app-feature-two>
并仅在导航到“ featuretwo”时才加载FeatureOneModule或在导航到“ featuretwo”时才加载FeatureTwoModule?
解决方法
由于您希望BaseComponent
出现在每条路线中,因此应将其包含在AppComponent组件中:
<app-base></app-base>
如果功能部件需要显示为基本部件的同级,只需相应地放置路由器电源插座即可:
<app-base></app-base>
<router-outlet></router-outlet>
如果功能组件应嵌套在baseComponent的某个部分中,则可以使用内容投影:
<app-base>
<router-outlet></router-outlet>
</app-base>
然后在您的BaseComponent中,使用ng-content
:
<header></header>
<ng-content></ng-content>
<footer></footer>
,
在当前配置下,因为{ path: '',component: BaseComponent },
是第一个,所以无论您发出什么URL,它都将始终解析为BaseComponent
。 Angular通过执行DFS搜索来解析路线,并且会在第一个匹配项处终止,因此在定义路线时必须保持简洁。
一种解决方法是添加pathMatch: 'full'
:
{ path: '',component: BaseComponent,pathMatch: 'full' },...
它将引发诸如“初始化前无法访问'FeatureOneModule'之类的错误”
您会收到此错误,因为app-feature-one
和app-feature-two
是属于延迟加载模块的组件,因此,除非您强制性地导入这些模块,否则您不会能够使用它们。
是否可以通过某种方式保留诸如“ featureone”和“ featuretwo”之类的路线...
解决此问题的一种快速方法是使用命名网点:
const routes: Routes = [
{
path: '',pathMatch: 'full',children: [
{ path: 'featureone',loadChildren: () => import('./feature-one/feature-one.module').then(m => m.FeatureOneModule),outlet: 'feat-one' },{ path: 'featuretwo',loadChildren: () => import('./feature-two/feature-two.module').then(m => m.FeatureTwoModule),outlet: 'feat2' },]
},{ path: '**',redirectTo: '',pathMatch: 'full'}
];
然后,在您的base-component.component.html
<router-outlet name="feat-one"></router-outlet>
<!-- ... -->
<router-outlet name="feat-two"></router-outlet>
要导航到其中一个(或同时导航到两者),您必须使用以下代码:
[routerLink]="[{ outlets: { 'feat-one': 'featureone' } ... }]"