假设我的 app.module.ts 中有这个
@NgModule({
imports: [
BrowserModule,
HttpModule,
RouterModule.forRoot([
{path: 'home', component: HomeComponent},
{path: '', redirectTo: 'home', pathMatch: 'full'},
{path: '**', component: NotFoundComponent},
]),
UserModule
...
})
在我看来,这导致了这个路由顺序:
{path: 'User', component: UserComponent},
{path: 'home', component: HomeComponent},
{path: '', redirectTo: 'home', pathMatch: 'full'},
{path: '**', component: NotFoundComponent}
请注意,用户现在在其他人之前。
现在我将RouterModule.ForRoot 部分导出到另一个名为AppRoutingModule 的模块。
@NgModule({
imports: [
BrowserModule,
HttpModule,
AppRoutingModule, // newly created routing module
UserModule
...
})
在我看来,这导致了这一点:
{path: 'home', component: HomeComponent},
{path: '', redirectTo: 'home', pathMatch: 'full'},
{path: '**', component: NotFoundComponent},
{path: 'User', component: UserComponent}
请注意,用户现在在其他人之后。
所以我必须把 AppRoutingModule 放在 UserModule 下面。为什么要这样实现?
最佳答案
以下是官方文档中的两个链接,可帮助您了解如何进行导入,以及如何了解当前的订单路线:
App.Module.ts
const appRoutes: Routes = [
{ path: 'crisis-center', component: CrisisListComponent },
{ path: 'hero/:id', component: HeroDetailComponent },
{
path: 'heroes',
component: HeroListComponent,
data: { title: 'Heroes List' }
},
{ path: '',
redirectTo: '/heroes',
pathMatch: 'full'
},
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
)
// other imports here
],
...
})
export class AppModule { }
The order of the routes in the configuration matters and this is by design. The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. In the configuration above, routes with a static path are listed first, followed by an empty path route, that matches the default route. The wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first.
App.Module.ts
// Diagnostic only: inspect router configuration
constructor(router: Router) {
console.log('Routes: ', JSON.stringify(router.config, undefined, 2));
}
关于Angular 2 - 为什么导入的模块路由顺序与固定编码不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46113920/