子路由模块

目前为止,我们的所有组件都是在app下面,并以app.module.ts为壳做加载。对于小应用是不受影响的,但是一旦需求复杂,组件变多的时候维护起来很困难,所以我们需要创建子模块来管理我们划分的子业务。

在app文件夹下面创建子模块:hero

1
ng generate module hero

 

可以看到创建了文件夹app/hero,并且创建了模块hero.module.ts

1
2
3
4
5
6
7
8
9
10
11
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [
    CommonModule,
  ],
  declarations: [
  ]
})
export class HeroModule { }

 

app/hero里面创建子路由hero-routing.module.ts

1
2
3
4
5
6
7
8
import { NgModule } from '@angular/core';
import { RouterModule, Routes} from '@angular/router';

@NgModule({
  imports: [
  ],  
})
export class HeroRoutingModule { }

 

注意将路由模块文件和他对应的模块文件放在同一层目录下。

在路由模块HeroRoutingMudole导入相关组件,并添加两个路由,然后导出HeroRoutingMudle类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { NgModule } from '@angular/core';
import { RouterModule, Routes} from '@angular/router';

import { HeroListComponent } from './hero-list/hero-list.component';

const HeroRouter: Routes = [
  {
    path: 'heroes',
    component: HeroListComponent,
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(HeroRouter),
  ],
  exports: [
    RouterModule
  ],
})
export class HeroRoutingModule { }

 

大部分写法和根模块中的路由写法一致,不同的是,根模块中我们使用了静态方法RouterModule.forRoot,而这里我们使用了RouterModule.forChild方法。只能在根模块中用forRoot方法来注册应用的顶级路由,在其他模块中使用forChild来注册附属路由。

把路由模块添加到HeroModule模块中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HeroRoutingModule } from './hero-routing.module';
import { HeroListComponent } from './hero-list/hero-list.component';

@NgModule({
  imports: [
    CommonModule,
    HeroRoutingModule,
  ],
  declarations: [
    HeroListComponent,
  ]
})
export class HeroModule { }

 

需要将创建好的子模块导入根模块才可以使用。

将模块HeroModule导入根模块AppModule并且加入大@NgModule元数据的imports数组里面:

1
2
3
4
5
6
7
import { HeroModule } from './hero/hero.module';

imports: [
  BrowserModule,
  HeroModule,
  AppRoutingModule,
],

 

注意imports的顺序,路由器会接受第一个匹配上导航所要求路径的那个路由。一旦将里面有通配符匹配的路由放前面,会导致后面的路由无法匹配而全部匹配到了通配符的路由。

现在,路由不再是单一的文件而是分散在各个模块中的路由文件。每个路由模块会根据加载顺序将自己的路由配置追加进去。

而且,这样的好处是,顶级路由有顶级路由文件来维护,附属路由有附属路由的文件来维护,管理起来也更方便。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值